2016-11-23 139 views
0

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

您的留言:从TestBeanScope南陈 警报您好: 您的留言:您好,从南陈

但实际上,输出是:

您的留言:您好,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> 

回答

0

据我了解,按照ClassPathXmlApplicationContext doc

在多个配置位置的情况下,后面的bean定义将覆盖前面加载的文件

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

+0

如何我可以做,如果我想要的输出是“您的消息:你好来自Nam Tran”。这意味着我必须将上下文对象传递给TestBeanScope类,这种方式并不是我期望的保持bean的一个实例。 –

+0

您可以使用注释'@ Autowired'或实现接口[ApplicationContextAware](http:// docs)注入ApplicationContext。 spring.io/spring/docs/current/javadoc-api/org/springframework/context/ApplicationContextAware.html) –

+0

我的意思是我想找到一个可以随处获得bean的特性。注入ApplicationContext不是我的方式。您可以想象使用Web应用程序的bean的会话范围。这是我想要的方式。 –