Non-singleton (prototype) Spring beans

I have Spring beans A and B. I’d like to have a new instance of B on each method invocation on A.
- First, A should be a singleton bean and B is a prototype bean.
- Bean A can be made to be aware of the container by implementing BeanFactoryAware like this:
public class BeanA implements BeanFactoryAware {
  private BeanFactory beanFactory;
  // setter for beanFactory
  public void needNewInstanceOfB() {
    (BeanB) beanFactory.getBean("beanB");
  }
}

Note: not a desirable solution since the business code is aware of and coupled to the Spring framework. So, use method injection.

public abstract class BeanA {
  public void needNewInstanceOfB() {
    BeanB newB = createNewB();
  }
  protected abstract BeanB createNewB();
}

<bean id=”beanB” class=”BeanB” scope=”prototype”/>
<bean id=”beanA” class=”BeanA”>
  <lookup-method name=”createNewB” bean=”beanB”/>
</bean>

Spring 3.0 & JUnit 4 test suites

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s


Follow

Get every new post delivered to your Inbox.