在Spring中避免子上下文覆盖父上下文的Bean

3
我在我的应用程序中有以下两个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中的“cache” 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”。
谢谢。

你可以使用Spring profiles吗? - approxiblue
1个回答

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

}

我希望我正确理解了您所寻求的内容。否则,请在回答中进行评论以讨论它。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接