Spring 事件發佈訂閱

Spring中事件的發佈訂閱機制

1.1

事件的發佈者發佈事件,事件的監聽這對對應的事件進行監聽,當監聽到對應的事件時,就會觸發調用相關的方法。因此,在事件處理中,事件是核心,是事件發佈者和事件監聽者的橋樑。

1.2

Spring 是基於Observer模式(java.util包中有對應實現),提供了針對Bean的事件發佈功能。
Spring中相關的主要有四個接口:ApplicationEvent,ApplicationEventPublisher,ApplicationEventPublisherAware,ApplicationListener.

1.2.1 ApplicationEvent

ApplicationEvent繼承自JavaSE中的EventObject,我們在使用的時候可以繼承這個接口來定義事件,進行信息的傳遞,因爲
ApplicationListener只接受ApplicationEvent或者他的子類。

1.2.2 ApplicationEventPublisher

事件的發佈接口,通過publishEvent(ApplicationEvent event)方法來發布消息。

1.2.3 ApplicationEventPublisherAware

這個接口的解釋是: Interface to be implemented by any object that wishes to be notified of the ApplicationEventPublisher (typically the ApplicationContext) that it runs in. (這是一個 任何想要實現通知正在運行的ApplicationEventPublisher的對象需要去實現的接口)。

通過這個接口的void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher)方法,將ApplicationEventPublisher注入進去,來進行消息通知。

1.2.4 ApplicationListener

監聽器接口,ApplicationListener中的void onApplicationEvent(E event)來接受消息事件,進行消息處理。


public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {

	/**
	 * Handle an application event.
	 * @param event the event to respond to
	 */
	void onApplicationEvent(E event);

}

通過源代碼發現,需要使用ApplicationEvent或者ApplicationEvent的子類。

1.3 具體使用

Event


public class MyEvent extends ApplicationEvent {
    private String words;

    public MyEvent(Object source,String words) {
        super(source);
        this.words = words;
    }

    public String getWords() {
        return words;
    }

    public void setWords(String words) {
        this.words = words;
    }
}

Aware


public class MyPublishAware implements ApplicationEventPublisherAware {

    public void sayHello() {
        MyEvent myEvent = new MyEvent(this, new String("helloWorld"));
        applicationEventPublisher.publishEvent(myEvent);
    }

    private ApplicationEventPublisher applicationEventPublisher;

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        
    }
}

Listenner


public class MyListenner implements ApplicationListener {
    @Override
    public void onApplicationEvent(MyEvent e) {
        System.out.println(e.getClass().toString());
        System.out.println(e.getWords());
    }
}

3.1 Spring自己定義的幾個ApplicationEvent的實現類

1)ContextRefreshedEvent:當ApplicationContext初始化或者刷新時觸發該事件。

2)ContextClosedEvent:當ApplicationContext被關閉時觸發該事件。容器被關閉時,其管理的所有單例Bean都被銷燬。

3)ContestStartedEvent:當容器調用ConfigurableApplicationContext的Start()方法開始/重新開始容器時觸發該事件。

4)ContestStopedEvent:當容器調用ConfigurableApplicationContext的Stop()方法停止容器時觸發該事件。

5)ApplicationContextEvent 這個是平時經常用到的。 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章