我的应用程序中有以下两个 xml 文件。应用程序上下文首先使用 parent.xml 进行初始化,然后使用代码使用 child.xml 进行更新:
context = FileSystemXmlApplicationContext(parentContext)
context.setConfigLocations(child xml path)
context.refresh()
parent.xml:
<bean id="cache" class="com.ICache"/>
child.xml:
<bean id="bean1" class="com.Class1">
<constructor-arg index="0" ref="cache"/>
</bean>
<bean id="bean2" class="com.Class2">
<constructor-arg index="0" ref="bean1"/>
</bean>
<bean id="bean3" class="com.Class3">
<constructor-arg index="0" ref="cache"/>
</bean>
<bean id="bean4" class="com.Class4">
<constructor-arg index="0" ref="bean3"/>
</bean>
我现在有一个用例,它要求我在 child.xml 中初始化的一些 bean 中交换“缓存”bean,这就是我所做的: 将以下配置添加到 parent.xml:
<bean id="newCache" class="com.ICache"/>
<bean id="bean3" class="com.Class3">
<constructor-arg index="0" ref="newCache"/>
</bean>
但是,这似乎不起作用,我认为这是因为 bean 的初始化顺序,当有多个 bean 具有相同的名称时,最后一个获胜。有没有办法不让父 bean 被子上下文中的 bean 覆盖?
此外,有没有办法在 spring 配置中添加条件逻辑(例如:如果 bean 已定义)?我想知道我是否可以修改我的 child.xml 中的一些 bean 以使用“newCache”(如果已定义则使用“cache”)。
谢谢。
最佳答案
我的建议是在Class3中为缓存提供一个setter:
public class Class3 {
private ICache cache;
public Class3(ICache cache){..}
public setICache(ICache cache) {
this.cache = cache;
}
}
如果你想在 ClassA 中交换 Class3 的缓存(ClassA 是 Class3 的客户端)实现 ApplicationContextAware 并更改 Class3 的缓存:
public class ClassA implements ApplicationContextAware {
@Autowire
Class3 class3;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
ICache cache = (ICache)applicationContext.getBean("newCache");
class3.setICache(cache);
}
}
希望我能正确理解您要查找的内容。否则评论答案以讨论它。
关于xml - 避免在 Spring 中子上下文从父上下文覆盖 beans,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32533537/