I understand Spring has configuration based inheritance, that means I can create beans referencing another bean as parent and Spring will copy the properties defined to the child. I'm looking on how to do the same with Java-based Spring configurations. I'll illustrate with the following example:
In Spring configurations I can define the following Properties
class for holding values:
package com.example
class Properties {
String valueA;
String valueB;
String valueC;
}
Later on a Spring XML configuration I can define the following 3 beans with configuration inheritance:
<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>
This results in propertiesBase
with someValueForA
, propertiesChild having someValueForA
and someValueForB
, finally propertiesGrandChild having someValueForA
, someValueForB
and someValueForC
I figure in Spring Java based configurations I can define something similar as this
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;
}
}
But this approach has the problem that, if the class Properties
changes, then all Bean
definitions needs to change accordingly to keep the values propagating. Is there another approach for this problem, that does not suffer from the latter problem?