假設豆A
是事件發佈者(觀察者),豆B1
,B2
和B3
是事件監聽者(觀察者)。用Spring XML配置實現觀察者模式?
所有B實現一些BEvenListener
接口。
如何在A
中對可觀察接口進行編碼?我希望編寫像通常的Java的addEventListener(BEventListener listener)
。
如何設置所有B在Spring配置中偵聽A
?平常的「setter」只允許一次注射,對吧?那麼,如何在Spring中配置「加法器」呢?
Spring提供了ApplicationListener
和ApplicationEventPublisherAware
它允許編寫監聽事件的bean,發佈到上下文中。但是這個機制沒有配置,即XML文件沒有說哪個bean監聽哪個。只有類型很重要,並且所有編碼爲監聽事件的bean都會在上下文中進行監聽。即事件是上下文範圍內的。
是否有可能在XML中配置發佈者和偵聽器之間的定向事件「通道」?
UPDATE
我還沒有唯一的想法是注入可觀察到過濾事件。
因此,班會
public class Observable implements ApplicationEventPublisherAware {
public static class Event extends ApplicationEvent {
public Event(Object source) {
super(source);
}
}
private ApplicationEventPublisher applicationEventPublisher;
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher value) {
this.applicationEventPublisher = value;
}
public void somecode() {
applicationEventPublisher.publishEvent(new Event(this));
}
}
和
public class Observer implements ApplicationListener<Observable.Event> {
private Observable observable;
public void setObservable(Observable value) {
this.observable = value;
}
@Override
public void onApplicationEvent(Event event) {
if(event.getSource() == observable) {
// process event
}
}
}
和配置將是
<bean id="observable" class="tests.observer.Observable"/>
<bean id="observer" class="tests.observer.Observer">
<property name="observable" ref="observable"/>
</bean>
這將使組發佈明確。
這可能會有幫助。 http://www.springindepth.com/book/in-depth-ioc-bean-post-processors-and-beanFactory-post-processors.html –