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.
You need to tell spring that you want a prototype bean rather than a singleton bean
This will get you a new instance with each request.