如何强制弹簧容器不返回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
给我一个新实例?
When I call getBean(name)
on a BeanFactory
, I get back an instance of the bean defined in the application context. However, when I call getBean(name)
again (with the same name,) I get the same instance of the bean back. I understand how this would be desirable in some (many?) cases, but how do I tell the BeanFactory
to give me a new instance?
示例Spring配置(简洁地说......我遗漏了一些冗长的内容,但这应该得到重点):
Example Spring configuration (tersely...I've left out some verbosity, but this should get the point across):
<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
}
当我运行这个时,我会得到类似的结果:
When I run this, I get something like:
misc.BeanClass@139894
misc.BeanClass@139894
请注意,两者都有相同的OOID ...所以这些是相同的实例...但我想要不同的实例。
Note that both have the same OOID...so these are the same instances...but I wanted different instances.
推荐答案
你需要告诉spring你想要一个原型bean而不是一个单例bean
You need to tell spring that you want a prototype bean rather than a singleton bean
<bean id="beanA" class="misc.BeanClass" scope="prototype"/>
这将为您提供每个请求的新实例。
This will get you a new instance with each request.
这篇关于如何强制弹簧容器不返回bean的单例实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!