如何修改spring容器中定义的bean

tan*_*ens 11 java spring ioc-container

我有两个xml文件定义springframework(版本2.5.x)的bean:

containerBase.xml:
<beans>
    <bean id="codebase" class="com.example.CodeBase">
        <property name="sourceCodeLocations">
            <list>
                <value>src/handmade/productive</value>
            </list>
        </property>
    </bean>
</beans>
Run Code Online (Sandbox Code Playgroud)

......和

containerSpecial.xml:
<beans>
    <import resource="containerBase.xml" />
</beans>
Run Code Online (Sandbox Code Playgroud)

现在我想调整财产sourceCodeLocationsbean的codebase范围内containerSpecial.xml.我需要添加第二个值src/generated/productive.

一个简单的方法是覆盖codebasein 的定义containerSpecial.xml并添加两个值,一个来自containerBase.xml和新的:

containerSpecial.xml:
<beans>
    <import resource="containerBase.xml" />

    <bean id="codebase" class="com.example.CodeBase">
        <property name="sourceCodeLocations">
            <list>
                <value>src/handmade/productive</value>
                <value>src/generated/productive</value>
            </list>
        </property>
    </bean>
</beans>
Run Code Online (Sandbox Code Playgroud)

有没有办法扩展列表而不重新定义bean?

编辑2009-10-06:

这样做的目的是拥有一个containerBase由许多不同项目使用的共享标准容器.每个项目都可以覆盖/扩展一些特定于该项目的属性containerSpecial.如果项目没有覆盖,则使用中定义的默认值containerBase.

Jas*_*man 8

在Spring容器实例化Code​​Base bean之前,您可以使用BeanFactoryPostProcessor来更改bean的元数据.例如:

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;
    }

}
Run Code Online (Sandbox Code Playgroud)

然后在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>
Run Code Online (Sandbox Code Playgroud)