2011-01-26 29 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>