我了解 Spring 具有基于配置的继承,这意味着我可以创建将另一个 bean 引用为父级的 bean,并且 Spring 会将定义的属性复制给子级。我正在研究如何对基于 Java 的 Spring 配置做同样的事情。我将通过以下示例进行说明:
在 Spring 配置中,我可以定义以下Properties
类来保存值:
package com.example
class Properties {
String valueA;
String valueB;
String valueC;
}
稍后在 Spring XML 配置中,我可以使用配置继承定义以下 3 个 bean:
<bean id="propertiesBase" class="com.example.Properties">
<property name="valueA" value="someValueForA"/>
</bean>
<bean id="propertiesChild" parent="propertiesBases">
<property name="valueB" value="someValueForB"/>
</bean>
<bean id="propertiesGrandChild" parent="propertiesChild">
<property name="valueC" value="someValueForC"/>
</bean>
这导致propertiesBase
with someValueForA
, propertiesChild 拥有someValueForA
和someValueForB
, 最后 propertiesGrandChild 拥有someValueForA
,someValueForB
和someValueForC
我想在基于 Spring Java 的配置中,我可以定义类似的东西
package com.example.config
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Bean;
import com.example.Properties;
@Configuration
class MyConfiguration {
@Bean(name = "propertiesBase")
Properties getPropertiesBase() {
Properties p = new Properties();
p.setValueA("someValueForA");
return p;
}
@Bean(name = "propertiesChild")
Properties getPropertiesChild(@Qualifier("propertiesBase") Properties parent) {
Properties p = new Properties();
p.setValueA(parent.getValueA());
p.setValueB("someValueForB");
return p;
}
@Bean(name = "propertiesGrandChild")
Properties getPropertiesGrandChild(@Qualifier("propertiesChild") Properties parent) {
Properties p = new Properties();
p.setValueA(parent.getValueA());
p.setValueB(parent.getValueB());
p.setValueC("someValueForC");
return p;
}
}
但是这种方法的问题是,如果类Properties
发生变化,那么所有Bean
定义都需要相应地变化以保持值的传播。这个问题是否有另一种方法,不会受到后一个问题的影响?