【问题标题】:Avoid child context override beans from parent context in Spring在 Spring 中避免子上下文覆盖来自父上下文的 bean
【发布时间】:2015-09-19 00:44:51
【问题描述】:

我的应用程序中有以下两个 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 被子上下文中的那些覆盖?

另外,有没有办法在 spring 配置中添加条件逻辑(例如:如果定义了 bean)?我想知道我是否可以修改 child.xml 中的一些 bean 以使用“newCache”,如果定义了,则使用“cache”。

谢谢。

【问题讨论】:

标签: xml spring


【解决方案1】:

我的建议是为 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);
  }

}

我希望我能正确理解您在寻找什么。否则评论答案以讨论它。

【讨论】:

    猜你喜欢
    • 2011-05-14
    • 2011-12-06
    • 1970-01-01
    • 1970-01-01
    • 2012-02-08
    • 2013-03-12
    • 1970-01-01
    • 1970-01-01
    • 2023-02-16
    相关资源
    最近更新 更多