我需要实例化一个原型bean,它有多个带参数和Autowired注入的构造函数。
我从这里找到的解决方案开始实例化bean: Spring bean with runtime constructor arguments
Bean定义
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
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);
}
}
测试类
@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
}
}
但是我的服务仍然没有注入,我在尝试拨打exampleCallService()
时获得了NPE。可能是因为手动调用了new MyBean()
。
我怎样才能正确实例化这样的bean?我使用的是spring 3.0.7