gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 13:46:32 30 4
gpt4 key购买 nike

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

containerBase.xml:
<beans>
<bean id="codebase" class="com.example.CodeBase">
<property name="sourceCodeLocations">
<list>
<value>src/handmade/productive</value>
</list>
</property>
</bean>
</beans>

...和

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

现在我想在 containerSpecial.xml 中调整 bean codebase 的属性 sourceCodeLocations。我需要添加第二个值 src/generated/productive

一种简单的方法是覆盖 containerSpecial.xmlcodebase 的定义并添加两个值,即 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>

有没有办法在不重新定义 bean 的情况下扩展列表?

编辑 2009-10-06:

这样做的目的是有一个共享的标准容器 containerBase 被许多不同的项目使用。每个项目都可以在其自己的 containerSpecial 中覆盖/扩展该项目的一些特殊属性。如果项目没有覆盖,它使用 containerBase 中定义的默认值。

最佳答案

您可以使用 BeanFactoryPostProcessor在 Spring 容器实例化 CodeBase bean 之前更改 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;
}

}

然后在 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>

关于java - 如何修改spring容器中定义的bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1486779/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com