我已经创建了一些类来测试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>
如何我可以做,如果我想要的输出是“您的消息:你好来自Nam Tran”。这意味着我必须将上下文对象传递给TestBeanScope类,这种方式并不是我期望的保持bean的一个实例。 –
您可以使用注释'@ Autowired'或实现接口[ApplicationContextAware](http:// docs)注入ApplicationContext。 spring.io/spring/docs/current/javadoc-api/org/springframework/context/ApplicationContextAware.html) –
我的意思是我想找到一个可以随处获得bean的特性。注入ApplicationContext不是我的方式。您可以想象使用Web应用程序的bean的会话范围。这是我想要的方式。 –