tags:

views:

385

answers:

3

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.

+4  A: 

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

duffymo
+1 for doc link. Thanks.
Jared
+7  A: 

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.

Arcane
This did it. Two things derailed me: 1. Initially, i was looking for an argument to getBean(String), instead of an attribute in the configuration... 2. In Spring 1.x (my previous spring experience), the attribute was called 'singleton', but that apparently doesn't work in 2.5.
Jared
Yes, they changed it to "scope" in Spring 2.x to accomodate request, session and global session.
duffymo
A: 

I have a related problem on this thread here :

http://stackoverflow.com/questions/540815/scope-definiton-of-a-bean-in-spring

see if you can help