SpringBoot深入分析講解監(jiān)聽器模式上
注:圖片來源于網絡
SpringBoot作為業(yè)內公認的優(yōu)秀開源框架,它的監(jiān)聽器是如何實現(xiàn)呢?在這里首先對一些基礎組件進行分析;
1、事件ApplicationEvent
ApplicationEvent是一個抽象類,idea上展開其繼承關系如圖:
可見SpringBoot所定義的事件類型是極為豐富的。
2、監(jiān)聽器ApplicationListener
ApplicationListener是一個接口,我們也可以通過實現(xiàn)這個接口來定義自己的監(jiā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)聽器關注的事件;
還有一種實現(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這一事件廣播器,繼承關系如圖所示:
SpringBoot如何傳播事件,有時間在下一篇博文進行整理,本文有哪些不對之處,也感謝大家的指正。
到此這篇關于SpringBoot深入分析講解監(jiān)聽器模式上的文章就介紹到這了,更多相關SpringBoot監(jiān)聽器模式內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
SpringBoot JPA出現(xiàn)錯誤:No identifier specified&nb
這篇文章主要介紹了SpringBoot JPA出現(xiàn)錯誤:No identifier specified for en解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-03-03Java中ShardingSphere 數據分片的實現(xiàn)
其實很多人對分庫分表多少都有點恐懼,我們今天用ShardingSphere 給大家演示數據分片,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-09-09海量數據去重排序bitmap(位圖法)在java中實現(xiàn)的兩種方法
今天小編就為大家分享一篇關于海量數據去重排序bitmap(位圖法)在java中實現(xiàn)的兩種方法,小編覺得內容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-02-02