如何强制弹簧容器不返回bean的单例实例?

时间:2022-10-30 09:09:21

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?

当我在BeanFactory上调用getBean(name)时,我得到了在应用程序上下文中定义的bean的实例。但是,当我再次调用getBean(name)时(使用相同的名称),我得到了相同的bean实例。我理解在某些(很多?)情况下这是如何可取的,但是如何告诉BeanFactory给我一个新实例呢?

Example Spring configuration (tersely...I've left out some verbosity, but this should get the point across):

示例Spring配置(简洁地说......我遗漏了一些冗长,但这应该得到重点):

<beans>
   <bean id="beanA" class="misc.BeanClass"/>
</beans>

Example 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

Note that both have the same OOID...so these are the same instances...but I wanted different instances.

请注意,两者都具有相同的OOID ...所以这些是相同的实例...但我想要不同的实例。

2 个解决方案

#1


You need to tell spring that you want a prototype bean rather than a singleton bean

你需要告诉spring你想要一个原型bean而不是一个单独的bean

<bean id="beanA" class="misc.BeanClass" scope="prototype"/>

This will get you a new instance with each request.

这将为您提供每个请求的新实例。

#2


The default scope is singleton, but you can set it to prototype, request, session, or global session.

默认范围是单例,但您可以将其设置为原型,请求,会话或全局会话。

#1


You need to tell spring that you want a prototype bean rather than a singleton bean

你需要告诉spring你想要一个原型bean而不是一个单独的bean

<bean id="beanA" class="misc.BeanClass" scope="prototype"/>

This will get you a new instance with each request.

这将为您提供每个请求的新实例。

#2


The default scope is singleton, but you can set it to prototype, request, session, or global session.

默认范围是单例,但您可以将其设置为原型,请求,会话或全局会话。