How to modify beans defined in a spring container How to modify beans defined in a spring container spring spring

How to modify beans defined in a spring container


You could use a BeanFactoryPostProcessor to change the bean's metadata before the Spring container instantiates the CodeBase bean. For example:

public class CodebaseOverrider implements BeanFactoryPostProcessor {    private List<String> sourceCodeLocations;    public void postProcessBeanFactory(            ConfigurableListableBeanFactory beanFactory) throws BeansException {                CodeBase codebase = (CodeBase)beanFactory.getBean("codebase");        if (sourceCodeLocations != null)        {            codebase.setSourceCodeLocations(sourceCodeLocations);        }    }    public void setSourceCodeLocations(List<String> sourceCodeLocations) {        this.sourceCodeLocations = sourceCodeLocations;    }}

Then in contextSpecial.xml:

<beans>    <import resource="context1.xml" />    <bean class="com.example.CodebaseOverrider">        <property name="sourceCodeLocations">            <list>                <value>src/handmade/productive</value>                <value>src/generated/productive</value>            </list>        </property>    </bean></beans>


Yes. A bean definition can have a "parent" attribute that references a parent bean definition. The new "child" definition inherits most of the properties of the parent and any of those properties can be overridden.

See Bean Definition Inheritance

Also you can use Collection Merging to merge the list property definition from the parent and child bean definitions. This way you can specify some list items in the parent bean definition and add more items to it in the child bean definition.


Is there a way to define the list in a properties or other configuration before hand?

It seems like the app configuration and wiring are tightly coupled. From my experience, if it is hard to do something in Spring, likely there is a different easier way to do it.