2011-01-26 43 views
3

根據Spring documentation on PropertyOverrideConfigurer,您不能用屬性覆蓋configurer機制覆蓋bean引用。也就是說,您只能提供文字值:使用PropertyOverrrideConfigurer覆蓋bean引用

指定的覆蓋值始終爲 文字值;他們不是 翻譯成bean引用。當XML bean 定義中的 原始值指定了bean引用時,這個約定也適用。

如果我仍然想要使用重寫屬性文件重新配置接線,解決方法是什麼?

我知道我可以回退注入不是引用的bean,而是它的名字。然後我可以使用屬性覆蓋機制覆蓋有線bean名稱。但是這個解決方案意味着依靠Spring - ApplicationContextAware接口和它的getBean(String)方法。有什麼更好的?

+0

https://jira.springsource.org/browse/SPR-4905 – 2011-01-26 08:40:10

回答

0

我覺得你很困惑PropertyOverrideConfigurerPropertyPlaceholderConfigurer。這兩者是相關的,非常相似,但有不同的行爲,包括後者不得不做這樣的事情的能力:

<property name="myProp"> 
    <ref bean="${x.y.z}" /> 
</property> 

其中x.y.z是包含一個bean名稱的屬性。

所以你可以使用外部屬性來改變你的接線PropertyPlaceholderConfigurer

編輯:另一種選擇是放棄XML配置,並使用@Bean-style config in Java。這給了java的表現力充分的靈活性,所以你可以做你喜歡的事情。

+0

感謝。我沒有想到佔位符,因爲我想要一個默認的接線定義(使用XML),並允許覆蓋不修改我的XML文件的人。這不是說如果我使用佔位符,我不能在XML中提供默認值嗎? – 2011-01-26 08:36:02

1

作爲skaffman在他們的回答評論中提到,spel是您所要求的解決方法。

這個例子對我的作品:

Dog.java

public class Dog { 

    private String name; 

    public String getName() { 
     return name; 
    } 

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

    @Override 
    public String toString() { 
     return ReflectionToStringBuilder.toString(this); 
    } 

} 

override.properties

#person.d=#{dog1} 
person.d=#{dog2} 

Person.java

@Component 
public class Person { 

    private Dog d = new Dog(); 

    { 
     d.setName("buster"); 
    } 

    public Dog getD() { 
     return d; 
    } 

    public void setD(Dog d) { 
     this.d = d; 
    } 

    @Override 
    public String toString() { 
     return ReflectionToStringBuilder.toString(this); 
    } 

} 

Main.java

public class Main { 

    public static void main(String[] args) { 
     ClassPathXmlApplicationContext c = new ClassPathXmlApplicationContext("sandbox/spring/dog/beans.xml"); 
     System.out.println(c.getBean("person")); 
    } 

} 

的beans.xml

<?xml version="1.0" encoding="UTF-8"?> 
<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" 
    xmlns:p="http://www.springframework.org/schema/p" 
    xmlns:c="http://www.springframework.org/schema/c" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
      http://www.springframework.org/schema/beans/spring-beans.xsd 
      http://www.springframework.org/schema/context 
      http://www.springframework.org/schema/context/spring-context.xsd"> 

    <context:component-scan base-package="sandbox.spring.dog"/> 

    <bean 
     class="org.springframework.beans.factory.config.PropertyOverrideConfigurer" 
     p:locations="classpath:/sandbox/spring/dog/override.properties"/> 

    <bean 
     id="dog1" 
     class="sandbox.spring.dog.Dog" 
     p:name="rover"/> 

    <bean 
     id="dog2" 
     class="sandbox.spring.dog.Dog" 
     p:name="spot"/>   

</beans>