011. Spring Bean单例与非单例 - Go语言中文社区

011. Spring Bean单例与非单例


1、创建Java项目:File -> New -> Java Project

2、引入必要jar包,项目结构如下
这里写图片描述

3、创建People实体类People.java

package com.spring.model;

public class People {

    private int id;
    private String name;

    public People() {
        super();
        System.out.println("Create People");
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "People [id=" + id + ", name=" + name + "]";
    }

}

4、创建spring配置文件applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--非单例模式,未调用前不实例化对象-->
    <bean id="prototypePeople" class="com.spring.model.People" scope="prototype">
        <property name="id" value="0"></property>
        <property name="name" value="prototypePeople"></property>
    </bean>

    <!--单例模式,加载applicationContext.xml时初始化对象-->
    <bean id="singletonPeople" class="com.spring.model.People" scope="singleton">
        <property name="id" value="0"></property>
        <property name="name" value="singletonPeople"></property>
    </bean>

</beans>

5、创建Spring测试类SpringUnit.java

package com.spring.junit;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringUnit {

    ClassPathXmlApplicationContext ctx = null;

    @Before
    public void setUp() throws Exception {
        ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
    }

    @Test
    public void test() {

        System.out.println(ctx.getBean("prototypePeople") == ctx.getBean("prototypePeople"));
        System.out.println(ctx.getBean("singletonPeople") == ctx.getBean("singletonPeople"));
    }

    @After
    public void tearDown() throws Exception {
        ctx.close();
    }

}

6、测试结果

... 省略Spring日志信息 ...

Create People
Create People
Create People
false
true

... 省略Spring日志信息 ...
版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/wu_teng_hui/article/details/73611239
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2019-08-27 14:51:20
  • 阅读 ( 1207 )
  • 分类:

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢