xml - 避免在 Spring 中子上下文从父上下文覆盖 beans

标签 xml spring

我的应用程序中有以下两个 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/

相关文章:

java - 使用 JDOM2 构建 XML 并添加数据

xml - XSLT:如何用所有 sibling 的串联替换第一个 sibling ?

java - 在 Spring 中读取双重/多重属性

java - 在 groovy bean 中注入(inject) Spring bean

javascript - 在 jBoss 6.2 和 jBoss 7.3 中部署应用程序时的不同响应

android - 如何在editText框的右下角显示editText字符限制??下面的例子

android - 如何使 ScrollView 中的某些小部件像标题一样不可滚动或粘在屏幕顶部

python - 使用 Python 的 ElementTree 查找顶级 xml 注释

Java - 如何将 HS256 与 JwtAccessTokenConverter 一起使用

java - IntelliJ IDEA 中标有编译器错误的代码在 Eclipse 中运行良好