SpringBoot深入分析講解監(jiān)聽器模式上

注:圖片來源于網(wǎng)絡(luò)
SpringBoot作為業(yè)內(nèi)公認(rèn)的優(yōu)秀開源框架,它的監(jiān)聽器是如何實現(xiàn)呢?在這里首先對一些基礎(chǔ)組件進(jìn)行分析;
1、事件ApplicationEvent
ApplicationEvent是一個抽象類,idea上展開其繼承關(guān)系如圖:

可見SpringBoot所定義的事件類型是極為豐富的。
2、監(jiān)聽器ApplicationListener
ApplicationListener是一個接口,我們也可以通過實現(xiàn)這個接口來定義自己的監(jiān)聽器,可以通過與事件初始化器方式相似的方式進(jìn)行加載。
@FunctionalInterface
public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {
/**
* Handle an application event.
* @param event the event to respond to
*/
void onApplicationEvent(E event);
}我們可以看到代碼中它接受一個上文中提到的事件泛型,這代表了此監(jiān)聽器關(guān)注的事件;
還有一種實現(xiàn)監(jiān)聽器的方式,即實現(xiàn)SmartApplicationListener接口,SmartApplicationListener繼承了ApplicationListener接口,通過這種方式實現(xiàn)監(jiān)聽器,可以同時注冊多個感興趣的事件,只需實現(xiàn)接口的supportsEventType方法即可;
public interface SmartApplicationListener extends ApplicationListener<ApplicationEvent>, Ordered {
/**
* Determine whether this listener actually supports the given event type.
* @param eventType the event type (never {@code null})
*/
boolean supportsEventType(Class<? extends ApplicationEvent> eventType);
/**
* Determine whether this listener actually supports the given source type.
* <p>The default implementation always returns {@code true}.
* @param sourceType the source type, or {@code null} if no source
*/
default boolean supportsSourceType(@Nullable Class<?> sourceType) {
return true;
}
/**
* Determine this listener's order in a set of listeners for the same event.
* <p>The default implementation returns {@link #LOWEST_PRECEDENCE}.
*/
@Override
default int getOrder() {
return LOWEST_PRECEDENCE;
}
}3、事件廣播器ApplicationEventMulticaster
ApplicationEventMulticaster是一個接口,定義了添加監(jiān)聽器、刪除監(jiān)聽器、傳播事件等方法;
SpringBoot為我們實現(xiàn)了SimpleApplicationEventMulticaster這一事件廣播器,繼承關(guān)系如圖所示:

SpringBoot如何傳播事件,有時間在下一篇博文進(jìn)行整理,本文有哪些不對之處,也感謝大家的指正。
到此這篇關(guān)于SpringBoot深入分析講解監(jiān)聽器模式上的文章就介紹到這了,更多相關(guān)SpringBoot監(jiān)聽器模式內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
詳解手把手Maven搭建SpringMVC+Spring+MyBatis框架(超級詳細(xì)版)
本篇文章主要介紹了手把手Maven搭建SpringMVC+Spring+MyBatis框架(超級詳細(xì)版),具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-12-12
Spring與Mybatis相結(jié)合實現(xiàn)多數(shù)據(jù)源切換功能
java中l(wèi)ist.forEach()和list.stream().forEach()區(qū)別
Java中實現(xiàn)線程的三種方式及對比_動力節(jié)點Java學(xué)院整理

