在以下Case中将创建多少个spring bean

时间:2017-07-28 11:51:43

标签: java spring

根据我的说法,只有一个bean应该被创建,因为我已经将范围视为单例,但是输出说的是不同的东西。任何人都可以请你详细说明以下内容,

HelloWorld.java

public class HelloWorld {
    private String message;

    public HelloWorld(String message) {
        System.out.println(message+ "bean created");
        this.message=message;
    }

    public void getMessage() {
        System.out.println("Your Message : " + message);
   }
}

Main.java

public class Main {
    public  static void main(String args[]) {

        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
        obj.getMessage();

        HelloWorld obj2 = (HelloWorld) context.getBean("helloWorld2");
        obj2.getMessage();
        obj.getMessage();

        System.out.println(obj.hashCode());
        System.out.println(obj.hashCode());
    }
}

的beans.xml

<bean id = "helloWorld" class = "HelloWorld" scope="singleton">
    <!--<property name = "message" value = "Hello World!"/>-->
    <constructor-arg value="HelloWorld1"/>
</bean>

<bean id = "helloWorld2" class = "HelloWorld" scope="singleton">
    <!--<property name = "message" value = "Hello World2!"/>-->
    <constructor-arg value="HelloWorld2"/>
</bean>

输出:

HelloWorld1bean created
HelloWorld2bean created
Your Message : HelloWorld1
Your Message : HelloWorld2
Your Message : HelloWorld1
935148943
935148943

2 个答案:

答案 0 :(得分:1)

绝对2 尝试打印obj2.hashcode。不是obj哈希码

答案 1 :(得分:0)

这里没有2个单独的bean会创建你为HelloWorld创建2个不同的bean

<bean id = "helloWorld" class = "HelloWorld" scope="singleton">
    <!--<property name = "message" value = "Hello World!"/>-->
    <constructor-arg value="HelloWorld1"/>
</bean>

<bean id = "helloWorld2" class = "HelloWorld" scope="singleton">
    <!--<property name = "message" value = "Hello World2!"/>-->
    <constructor-arg value="HelloWorld2"/>
</bean>

Spring容器每个定义创建1个对象,如果我们定义bean N次,则会创建类的N单个对象