2013-07-26 81 views
0

我嘗試使用MyClass擴展PropertyPlaceholderConfigurer,並通過Autowired註釋爲Prop1和基於XML的Prop2注入屬性。 Prop1按預期工作,而Prop1爲空。我的代碼在下面有什麼問題嗎?當PropertyPlaceholderConfigurer被擴展時,我無法使用註釋擴展類

<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

由於MyClassBeanFactoryPostProcessor,它完全實例化的bean的生命週期非常早,才能夠採取行動創建的bean定義。另一方面,@Autowired註釋由AutoWiredAnnotationPostProcessor處理,它是BeanPostProcessor

現在由於MyClass已經完全實例化得更早,因此AutowiredAnnotationPostProcessor無法對其執行操作並注入prop1依賴關係,從而導致失敗。通過顯式配置本身將更好地注入BeanFactoryPostProcessor的所有屬性。

編輯: 的javadoc爲@Autowired有一個很好的解釋也 - http://static.springsource.org/spring/docs/3.2.x/javadoc-api/org/springframework/beans/factory/annotation/Autowired.html

+0

我appreaciate你的答案,並會讀你接受這個作爲一個答案之前給了參考,也你有一個錯字,它不是PROP2說失敗,其prop1。 – jchips12