Injecting additional values after initial bean initialization
I have a situation where a bean is originally defined by a project to be used in a specific runtime environment. However, this project is also used in a different runtime environment that would either
- like to redefine a specific bean
- or (better) inject some additional values into the already initialized bean.
I hate overwriting beans, can get very confusing, so I want to try the second option.
A more concrete example:
base.xml might include
<bean id="xxx" class="yyy"> <constructor-arg> <map> <entry key="key1" value="val1"/> </map> </constructor-arg> </bean>
This bean is used all over the place in project A.
Project B uses project A, loads all its spring configuration, but needs to add another value to the bean's map.
Something like.. I dunno
<bean id="xxx1" class="yyy" parent="xxx"> <property name="additionalMapValues"> <map> <entry key="key1" value="val1"/> </map> </property> </bean>
Don't really care about the new bean, I want to affect the original bean. Any way to do this?
If it's just additional map properties (or other collection properties) that you need in the new bean, you can use Spring's collection merging functionality. For example - similar to what you'd already shown, project A might declare:
<bean id="xxx" class="yyy"> <property name="mapValues"> <map> <entry key="key1" value="val1"/> </map> </property> </bean>
And then in project B, you can create a new bean definition that extends this - and merge in any new properties using the merge="true" attribute.
<bean id="xxx1" parent="xxx"> <property name="mapValues"> <map merge="true"> <entry key="key2" value="val2"/> </map> </property> </bean>
Note that both beans would be concrete in this case. So parent bean xxx would only include key1 whereas child bean xxx1 would just include both key1 and key2.