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?
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>
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.
But why singleton? When a service is stateless, it's thread-safe, and it can scale to any number of concurrent requests, so there's no need for a second copy of the same service. Unlike EJB, where there's stateful and stateless beans, Spring has only one type of bean: stateless.
Spring beans configured inside Java configuration classes are singleton by default. Therefore, it is not required to explicitly set the bean type. In order to set the Spring bean type to Singleton or Prototype, you will need to define the bean scope.
When you work with a prototype bean in a singleton, you have three options to get a new instance of the prototype: Spring can autowire a single prototype instance when it creates the singleton. It's the default framework behavior. Spring can create a new prototype instance on every call to any method of this prototype.
Singleton beans are created when the Spring container is created and are destroyed when the container is destroyed. Singleton beans are shared; only one instance of a singleton bean is created per Spring container. Singleton scope is the default scope for a Spring 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.
The default scope is singleton, but you can set it to prototype, request, session, or global session.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With