Spring Event


Spring Event 是基於觀察者模式實現,介紹其之前,我們先介紹下JDK提供的觀察者模型

觀察者:Observer,

 

被觀察:Observable

 

 

當被觀察者改變時,其需要通知所有關聯的觀察者。Observable實現邏輯如下:

1、 Observable定義了一個數據結構:Vector<Observer>,記錄關聯的Observer。
2、 通知關聯的觀察者:調用方法notifyObservers(調用所有Observer的update方法)。

 

好了,下面我們介紹Spring基於觀察者模式的Event機制

首先介紹Spring Event的關鍵的類

1、 ApplicationEvent 事件

2、 ApplicationListener 監聽(Observer)

3、 ApplicationEventPublisher 發布(Observable)

 

整體邏輯如下:

ApplicationEventPublisher發布ApplicationEvent給關聯的ApplicationListener。

 

根據觀察者模式,我們可以推導出來:

       ApplicationEventPublisher持有關聯的ApplicationListener列表,調用ApplicationListener的方法(將ApplicationEvent作為入參傳入過去),達到通知的效果。但問題來了,ApplicationEventPublisher如何知道這個ApplicationListener發給哪個ApplicationListener呢?

下面我們一步一步解析。

ApplicationListener(Observer)

 

ApplicationEventPublisher(Observable)

正在實現ApplicationEventPublisher.publishEvent這個方法的有兩個類

有兩個類AbstractApplicationContext和它的子類SimpleApplicationEventMulticaster

 

AbstractApplicationContext功能是存放所有關聯的ApplicationListener。數據結構如下:

Map<ListenerCacheKey, ListenerRetriever> retrieverCache。

ListenerCacheKey構成:

1、ResolvableType eventType(對應的是ApplicationEvent)

2、Class<?> sourceType(對應的是EventObject)

ListenerRetriever構成:

1、 Set<ApplicationListener<?>> applicationListeners(監聽)

答案很顯然,ApplicationEventPublisher是通過ApplicationEvent(繼承ApplicationEvent的Class類)類型來關聯需要調用的ApplicationListener。

 SimpleApplicationEventMulticaster的功能是:多線程調用所有關聯的ApplicationListener的onApplicationEvent方法的。

實踐:

創建Event

public class Event extends ApplicationEvent {
    private String message;
    public Event(Object source, String message) {
        super(source);
        this.message = message;
    }
    public String getMessage() {
        return message;
    }
}

創建監聽:

1、實現ApplicationListener
@Component
public class ImplementsListener implements ApplicationListener<Event> {
    @Override
    public void onApplicationEvent(Event event) {
        //TODO
    }
}
2、加@EventListener注解
@Component
public class AnnotationListener {
    @EventListener
    public void eventListener(Event event) {
        //TODO
    }
}

事件發布:

@Component
public class EventPublisher {
    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;
    public void publish() {
        applicationEventPublisher.publishEvent(new Event(this, "it's demo"));
    }
}

自定義事件廣播:

@Component(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)
public class CustomApplicationEventMulticaster extends AbstractApplicationEventMulticaster {
    @Override public void multicastEvent(ApplicationEvent event) {
        //TODO custom invokeListener(listener, event);
    }
    @Override public void multicastEvent(ApplicationEvent event, ResolvableType eventType) {
        //TODO custom invokeListener(listener, event);
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM