根据 Spring documentation on PropertyOverrideConfigurer您不能使用属性覆盖配置器机制覆盖 bean 引用。也就是说,您只能提供文字值:
Specified override values are always literal values; they are not translated into bean references. This convention also applies when the original value in the XML bean definition specifies a bean reference.
如果我仍想使用覆盖属性文件重新配置接线,有什么解决方法?
我知道我可以回退到不注入(inject)引用的 bean,而是注入(inject)它的名称。然后我可以使用属性覆盖机制覆盖有线 bean 名称。但该解决方案意味着依赖于 Spring - ApplicationContextAware
接口(interface)及其 getBean(String)
方法。还有更好的吗?
最佳答案
正如 skaffman 在他们的回答评论中提到的那样,spel是您要求的解决方法。
这个例子对我有用:
狗.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);
}
}
覆盖.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);
}
}
主.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>
关于java - 使用 PropertyOverrrideConfigurer 覆盖 bean 引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4802504/