Spring中Singleton范围内Bean的实例

时间:2016-11-23 03:00:34

标签: spring javabeans

我已经创建了一些类来测试Spring中的Bean范围,如下所示 据我所知,如果范围是singelton,那么Spring总是只为helloWorld对象提供一个实例。这意味着当我运行程序时,输出将是

您的留言:来自Nam Tran的您好 来自TestBeanScope的警报: 您的留言:来自Nam Tran的您好

但实际上,输出是:

您的留言:来自Nam Tran的您好 来自TestBeanScope的警报: 您的留言:Hello World!

你能解释一下原因吗?

===

package namtran.tutorial;

public class HelloWorld {
       private String message;

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

==========

package namtran.tutorial;

import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestBeanScope {
    public void getMessage(){
        @SuppressWarnings("resource")
        AbstractApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
        HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
         System.out.println("Alert from TestBeanScope:\n");
        obj.getMessage();
    }
}

=============

package namtran.tutorial;

import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {

    public static void main(String[] args) {
      @SuppressWarnings("resource")
      AbstractApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");

      HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
      obj.setMessage("Hello from Nam Tran");
      obj.getMessage();

      context.registerShutdownHook();
      TestBeanScope obj1 = new TestBeanScope();
      obj1.getMessage();

    }
}

====的beans.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-3.0.xsd">

  <bean id="helloWorld" 
       class="namtran.tutorial.HelloWorld" scope="singleton">
       <property name="message" value="Hello World!"/>
   </bean>
</beans>

1 个答案:

答案 0 :(得分:0)

据我了解,请按照ClassPathXmlApplicationContext doc

进行操作
  

如果有多个配置位置,以后的bean定义将覆盖先前加载的文件中定义的那些

当您首次在主方法中创建上下文并设置message时,它将打印
Your Message : Hello from Nam Tran
然后,您在TestBeanScope中创建了新的上下文,以便helloWorld bean将被覆盖。它的消息将是Hello World!,因为它是在Beans.xml中声明的。因此,消息是
Alert from TestBeanScope: Hello World!