Instantiate Spring prototype bean with arguments and injections
I need to instantiate a prototype bean which has multiple constructors with arguments and Autowired injections.
I started with the solution found here to instantiate the bean: Spring bean with runtime constructor arguments
Bean Definition
public MyBean {
@Autowired
private MyService myService
public MyBean(int a1, String a21, String a22) {
}
public MyBean(int a1, String[] a2, int a3) {
}
public void exampleCallService(int value) {
myService.remoteMethod(value);
}
}
Spring Configuration
@Configuration
public AppConfig {
@Bean("myBeanV1")
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public MyBean myBeanV1(int a1, String a21, String a22) {
return new MyBean(a1, a21, a22);
}
@Bean("myBeanV2")
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public MyBean myBeanV2(int a1, String[] a2, int a3) {
return new MyBean(a1, a2, a3);
}
}
Test Class
@Component
public class ExampleTest {
@Autowired
private MyService myService
@Autowired
private BeanFactory beanFactory;
public String exampleMethod(){
MyBean myBean = (MyBean) beanFactory.getBean("myBeanV1", 1, "a", "b");
myService.remoteMethod(42); // OK
myBean.exampleCallService(42); // NPE
}
}
But my service is still not injected and I get an NPE when trying to call exampleCallService()
. Probably because of the manual call to new MyBean()
. How can I properly instantiate such bean ? I am using spring 3.0.7