2012-11-08 58 views
2

假設豆A是事件發佈者(觀察者),豆B1,B2B3是事件監聽者(觀察者)。用Spring XML配置實現觀察者模式?

所有B實現一些BEvenListener接口。

如何在A中對可觀察接口進行編碼?我希望編寫像通常的Java的addEventListener(BEventListener listener)

如何設置所有B在Spring配置中偵聽A?平常的「setter」只允許一次注射,對吧?那麼,如何在Spring中配置「加法器」呢?

Spring提供了ApplicationListenerApplicationEventPublisherAware它允許編寫監聽事件的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> 

這將使組發佈明確。

+0

這可能會有幫助。 http://www.springindepth.com/book/in-depth-ioc-bean-post-processors-and-beanFactory-post-processors.html –

回答

0

這是我希望Spring會添加到他們的XML配置中的東西,但是如果您想避免將代碼綁定到Spring,您必須使用MethodInvokingFactoryBean

對於這個例子的目的,假設下面的方法已經加入你的tests.observer.Observable

void addObserver(Observer observer);

<bean id="observable" class="tests.observer.Observable"/> 

<bean id="observer" class="tests.observer.Observer"> 
    <property name="observable" ref="observable"/> 
</bean> 

<bean id="addObserver" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"> 
    <property name="targetObject" ref="observable" /> 
    <property name="targetMethod" value="addObserver"/> 
    <property name="arguments"> 
     <list> 
      <ref bean="observer" /> 
     </list> 
    </property> 
</bean>