我有一些以编程方式创建的 bean,我正在通过 AutowireCapableBeanFactory.autowireBean() 初始化它们,如下所示:
spring.xml:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<context:annotation-config/>
<bean id="MyService" class="...">
<property name="someProp" value="primitiveValue"/>
</bean>
<bean id="MyBean" class="...">
<property name="someString" value="primitiveValue"/>
</bean>
</beans>
MyBean.java
public class MyBean implements InitializingBean {
@Autowired MyService myService;
private String someString;
public void setSomeString (String someString) {
this.someString = someString;
}
public void afterPropertiesSet () {}
}
来电者:
MyBean bean = new MyBean(arg1, arg2, arg3);
autowireCapableBeanFactory.autowireBean(bean);
这会按预期正确 Autowiring bean.myService
。但是,它不会填充像 bean.someString
这样的原始属性。
查看文档和 this answer ,我认为这样的事情会起作用:
MyBean bean = new MyBean(arg1, arg2, arg3);
autowireCapableBeanFactory.autowireBean(bean);
autowireCapableBeanFactory.initializeBean(bean, "name");
但是可惜,someString
仍然是null
。我找到了很多引用资料,说明什么不能用于初始化类属性,但没有任何内容表明什么可以工作。
有什么想法吗?
发现我可以使用AutowireCapableBeanFactory.applyBeanPropertyValues()
来完成我想要的。注入(inject) @Autowired
beans 和原始属性的代码如下所示:
@Autowired AutowireCapableBeanFactory beanFactory;
...
MyBean bean = new MyBean();
beanFactory.autowireBean(bean);
beanFactory.applyBeanPropertyValues(bean, bean.getClass().getSimpleName());
我是一名优秀的程序员,十分优秀!