springBoot的事件機制GenericApplicationListener用法解析
什么是ApplicationContext?
它是Spring的核心,Context我們通常解釋為上下文環(huán)境,但是理解成容器會更好些。 ApplicationContext則是應(yīng)用的容器。
Spring把Bean(object)放在容器中,需要用就通過get方法取出來。
ApplicationEvent
- 是個抽象類,里面只有一個構(gòu)造函數(shù)和一個長整型的timestamp。
- springboot的event的類型:
- ApplicationStartingEvent
- ApplicationEnvironmentPreparedEvent
- ApplicationContextInitializedEvent
- ApplicationPreparedEvent
- ContextRefreshedEvent
- ServletWebServerInitializedEvent
- ApplicationStartedEvent
- ApplicationReadyEvent
ApplicationListener
是一個接口,里面只有一個onApplicationEvent方法。所以自己的類在實現(xiàn)該接口的時候,要實現(xiàn)該方法。
ApplicationListener的封裝類
- GenericApplicationListener
- GenericApplicationListenerAdapter
- SmartApplicationListener
關(guān)系
如果在上下文中部署一個實現(xiàn)了ApplicationListener接口的bean,那么每當(dāng)在一個ApplicationEvent發(fā)布到 ApplicationContext時,這個bean得到通知。其實這就是標(biāo)準(zhǔn)的Oberver設(shè)計模式。
注意
要配置META-INF/spring.factories文件,并在文件中實現(xiàn)
使用
// 第一種方式
public class AiInfluxdbApplicationListener implements GenericApplicationListener {
@Override
public int getOrder() {
return Ordered.LOWEST_PRECEDENCE;
}
@Override
public boolean supportsEventType(ResolvableType eventType) {
return ApplicationReadyEvent.class.isAssignableFrom(eventType.getRawClass());
}
@Override
public void onApplicationEvent(ApplicationEvent event) {
System.out.print("here is ApplicationReadyEvent");
}
}
//第二種方式
public class ConfigApplicationListener implements ApplicationListener<ApplicationEnvironmentPreparedEvent>, Ordered {
@Override
public int getOrder() {
return HIGHEST_PRECEDENCE;
}
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
}
}
//META-INF/spring.factories文件定義
org.springframework.context.ApplicationListener=\
com.demotest.core.ApplicationStartListener
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Intellij IDEA下Spring Boot熱切換配置
這篇文章主要介紹了Intellij IDEA下Spring Boot熱切換配置,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-08-08
Java function函數(shù)式接口的使用方法與實例
這篇文章主要介紹了Java function函數(shù)式接口的使用方法與實例,函數(shù)式接口如一支未完成的詩篇,用Lambda表達(dá)式作韻腳,將代碼的機械美感與藝術(shù)的抽象融為一體,悄然重構(gòu)了開發(fā)者對代碼之美的認(rèn)知,需要的朋友可以參考下2025-02-02
如何使用spring gateway微服務(wù)網(wǎng)關(guān)(基本用法)
本文介紹spring gateway的使用,包括配置文件的使用和調(diào)試跟蹤,讓大家了解spring gateway的基本用法,感興趣的朋友跟隨小編一起看看吧2024-08-08
Springboot整合RabbitMq測試TTL的方法詳解
這篇文章主要介紹了Springboot整合RabbitMq測試TTL的設(shè)置,設(shè)置TTL一般由兩種設(shè)置方法,設(shè)置整個隊列的過期時間另一種設(shè)置單個消息的過期時間,通過示例圖文相結(jié)合給大家介紹的非常詳細(xì),需要的朋友可以參考下2022-03-03
JavaWeb中JavaMail創(chuàng)建郵件和發(fā)送郵件
這篇文章主要介紹了JavaWeb中JavaMail創(chuàng)建郵件和發(fā)送郵件,較為詳細(xì)的分析了JavaMail發(fā)送郵件的用法,是非常實用的技巧,需要的朋友可以參考下2015-12-12
sqlserver和java將resultSet中的記錄轉(zhuǎn)換為學(xué)生對象
這篇文章主要介紹了如何利用sqlserver和java將resultSet中的記錄轉(zhuǎn)換為學(xué)生對象,附有超詳細(xì)的代碼,需要的朋友可以參考一下,希望對你有所幫助2021-12-12
使用Java如何將圖片轉(zhuǎn)成Base64編碼,并壓縮至40k
這篇文章主要介紹了使用Java如何將圖片轉(zhuǎn)成Base64編碼,并壓縮至40k問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-06-06

