我已經創建了一些類來測試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的會話範圍。這是我想要的方式。 –