![](/img/trans.png)
[英]How do I call another Singleton bean from a Singleton bean?
[英]How do I force a spring container not to return a singleton instance of a bean?
當我在BeanFactory
上調用getBean(name)
時,我會返回應用程序上下文中定義的bean實例。 但是,當我再次調用getBean(name)
時(使用相同的名稱),我得到了相同的bean實例。 我理解這在某些(很多?)情況下是如何需要的,但是如何告訴BeanFactory
給我一個新實例呢?
示例Spring配置(簡潔地說......我遺漏了一些冗長,但這應該得到重點):
<beans>
<bean id="beanA" class="misc.BeanClass"/>
</beans>
示例Java:
for(int i = 0;i++;i<=1) {
ApplicationContext context = ClassPathXmlApplicationContext("context.xml");
Object o = context.getBean("beanA");
System.out.println(o.toString()); // Note: misc.BeanA does not implement
// toString(), so this will display the OOID
// so that we can tell if it's the same
// instance
}
當我運行這個時,我會得到類似的東西:
misc.BeanClass@139894
misc.BeanClass@139894
請注意,兩者都具有相同的OOID ...所以這些是相同的實例...但我想要不同的實例。
你需要告訴spring你想要一個原型bean而不是一個單獨的bean
<bean id="beanA" class="misc.BeanClass" scope="prototype"/>
這將為您提供每個請求的新實例。
默認范圍是單例,但您可以將其設置為原型,請求,會話或全局會話。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.