[英]Avoiding circular dependencies in Spring beans with list properties
假设我有一个使用Spring框架的Maven项目。 Maven项目本身具有三个模块: common
, component_a
和component_b
。 假设common
定义了一个带有属性listeners
的事件侦听器bean,该侦听器bean是所有侦听事件的列表。 侦听器在component_a
和component_b
模块中定义。
总结一下:
applicationcontext-component_a.xml:
<beans>
<bean id="someListener" class="com.whatever.component_a.SomeListener"/>
<bean id="anotherListener" class="com.whatever.component_a.AnotherListener"/>
</beans>
applicationcontext-component_b.xml:
<beans>
<bean id="yetAnotherListener" class="com.whatever.component_b.YetAnotherListener"/>
</beans>
applicationcontext-common.xml:
<beans>
<bean id="eventListener" class="com.whatever.common.EventListenerImpl">
<property name="listeners">
<list>
<ref bean="someListener"/>
<ref bean="anotherListener"/>
<ref bean="yetAnotherListener"/>
</list>
</property>
</bean>
</beans>
(我想我的格式就在这里...但是如果我不原谅我)
我的问题是,现在common
依赖于两个component_*
模块,而不是相反的方式。 我的common
模块不再正确构建,因为如果没有其他模块,我的集成测试将无法正确创建容器。
因此,考虑到我的eventListener
需要具有所有侦听器的列表这一事实,有什么好用的模式可以使我的模块在构建/测试期间保持独立?
我可以想到一些模式:
eventListener
setEventListener()
调用中,请记住调用eventListener.addListener(this);
但是我很好奇Spring是否有任何内置方法可以更好地做到这一点...
您可以做的是在主模块中自动装配侦听器列表。 然后,每个其他模块都可以仅提供此接口的实现以及适当的componentscan / xml声明。
主模块:(伪代码)
@Service
ListenerService {
@Autowire
List<ListenerIntf> listeners;
public handleListeners() {
foreach listeners {
listener.onEvent();
}
}
}
模块1:
@Component
@Order // if desired
Listener1 implements ListenerIntf {
public onEvent();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.