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:
- 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>
<bean id=”beanA” class=”BeanA”>
<lookup-method name=”createNewB” bean=”beanB”/>
</bean>

Advertisement