AutowireCapableBeanFactory:如何初始化基本属性

时间:2017-12-15 00:21:39

标签: java spring autowired

我有一些以编程方式创建的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);

这正确地按预期自动bean.myService。但是它不会填充像bean.someString这样的原始属性。

查看文档和this answer,我会发现这样的事情:

MyBean bean = new MyBean(arg1, arg2, arg3);
autowireCapableBeanFactory.autowireBean(bean);
autowireCapableBeanFactory.initializeBean(bean, "name");

但是,唉,someString仍然是null。我找到了许多引用,说明不会用于初始化类属性,但没有显示工作的内容。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

发现我可以使用AutowireCapableBeanFactory.applyBeanPropertyValues()来完成我想要的。注入@Autowired bean和原始属性的代码如下所示:

@Autowired AutowireCapableBeanFactory beanFactory;

...

MyBean bean = new MyBean();
beanFactory.autowireBean(bean);
beanFactory.applyBeanPropertyValues(bean, bean.getClass().getSimpleName());