扩展PropertyPlaceholderConfigurer时,我无法对扩展类使用注释

时间:2013-07-26 10:26:28

标签: java spring

我尝试使用MyClass扩展PropertyPlaceholderConfigurer,并通过Prop1的Autowired注释和Prop2的基于XML的注入注入属性。 Prop2按预期工作,而Prop1为null。我的代码下面有什么问题吗?

<context:component-scan base-package="com.jchips12.test" />

<bean id="prop1" class="com.jchips12.test.Prop1">
    <property name="name" value="Prop1" />
</bean>

<bean id="myClass" class="com.jchips12.test.MyClass">
    <property name="prop2">
        <bean class="com.jchips12.test.Prop2">
            <property name="name" value="Prop2" />
        </bean>
    </property>
    <property name="location" value="classpath:environment.properties" />
</bean>

MyClass.java

public class MyClass extends PropertyPlaceholderConfigurer{

    @Autowired
    private Prop1 prop1;
    private Prop2 prop2;

    public void setProp2(Prop2 prop2) {
        this.prop2 = prop2;
    }

    ...

}

Prop1和Prop2

public class Prop1 {

    private String name;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

}

public class Prop2 {

    private String name;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

}

1 个答案:

答案 0 :(得分:1)

由于MyClassBeanFactoryPostProcessor,因此它在bean生命周期的早期完全实例化,以便能够对创建的bean定义进行操作。另一方面,@Autowired注释由AutoWiredAnnotationPostProcessor处理,它是BeanPostProcessor

现在因为MyClass更早地完全实例化,AutowiredAnnotationPostProcessor不能对它起作用并注入prop1依赖项,因此失败。最好通过显式配置本身注入BeanFactoryPostProcessor的所有属性。

编辑: @Autowired的javadoc也有一个很好的解释 - http://static.springsource.org/spring/docs/3.2.x/javadoc-api/org/springframework/beans/factory/annotation/Autowired.html