SpringBoot中的ApplicationListener事件監(jiān)聽器使用詳解
ApplicationListener
ApplicationListener是應(yīng)用程序的事件監(jiān)聽器,繼承自java.util.EventListener標(biāo)準(zhǔn)接口,采用觀察者設(shè)計(jì)模式。
從spring3.0開始,ApplicationListener可以指定要監(jiān)聽的事件類型,當(dāng)spring的上下文環(huán)境ApplicationContext時(shí),當(dāng)指定事件發(fā)布的時(shí)候,對應(yīng)事件的事件監(jiān)聽器將被調(diào)用。
使用ApplicationListener需要三元素,事件,監(jiān)聽,事件發(fā)布。
ApplicationListener應(yīng)用
1.新建事件
繼承自ApplicationEvent .
public class TestApplicationEvent extends ApplicationEvent {
/**
* Create a new ApplicationEvent.
*
* @param test the object on which the event initially occurred (never {@code null})
*/
public TestApplicationEvent(TestApplication test) {
super(test);
}
}2.新建監(jiān)聽器
實(shí)現(xiàn)ApplicationListener指定要監(jiān)聽的事件類型,監(jiān)聽器必須注入容器當(dāng)中可以使用注解方式(例如:@Component),或者在資源路徑下新建META-INF/spring.factories文件導(dǎo)入
@Component
public class TestApplicationListener implements ApplicationListener<TestApplicationEvent> {
@Override
public void onApplicationEvent(TestApplicationEvent event) {
System.out.println(event.getSource());
}
}
3.事件發(fā)布
當(dāng)spring應(yīng)用上下文環(huán)境初始化完畢,進(jìn)行事件的發(fā)布
@SpringBootApplication
public class CommonsTestApplication {
public static void main(String[] args) {
ConfigurableApplicationContext applicationContext = SpringApplication
.run(CommonsTestApplication.class, args);
TestApplication testApplication = new TestApplication();
testApplication.setName("zhangsan");
testApplication.setAge(23);
TestApplicationEvent testApplicationEvent = new TestApplicationEvent(testApplication);
applicationContext.publishEvent(testApplicationEvent);//事件發(fā)布時(shí),指定的監(jiān)聽器就進(jìn)行接收
}
}4.啟動程序
當(dāng)容器初始化完畢后,發(fā)布事件,事件監(jiān)聽器進(jìn)行接收。

到此這篇關(guān)于SpringBoot中的ApplicationListener事件監(jiān)聽器使用詳解的文章就介紹到這了,更多相關(guān)ApplicationListener事件監(jiān)聽器使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Springboot整合Druid實(shí)現(xiàn)對訪問的監(jiān)控方式
這篇文章主要介紹了Springboot整合Druid實(shí)現(xiàn)對訪問的監(jiān)控方式,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-05-05
Java的Struts框架中登陸功能的實(shí)現(xiàn)和表單處理器的使用
這篇文章主要介紹了Java的Struts框架中登陸功能的實(shí)現(xiàn)和表單處理器的使用,Struts框架是Java的SSH三大web開發(fā)框架之一,需要的朋友可以參考下2015-12-12
SpringBoot使用GraphQL開發(fā)Web API實(shí)現(xiàn)方案示例講解
這篇文章主要介紹了SpringBoot使用GraphQL開發(fā)Web API實(shí)現(xiàn)方案,GraphQL是一個(gè)從服務(wù)端檢數(shù)據(jù)的查詢語言。某種程度上,是REST、SOAP、或者gRPC的替代品2023-04-04
Java實(shí)現(xiàn)Map集合二級聯(lián)動示例
Java實(shí)現(xiàn)Map集合二級聯(lián)動示例,需要的朋友可以參考下2014-03-03
關(guān)于Redis鍵值出現(xiàn)\xac\xed\x00\x05t\x00&錯誤的解決方法
這篇文章主要介紹了關(guān)于Redis鍵值出現(xiàn)\xac\xed\x00\x05t\x00&的解決方法,出現(xiàn)該問題的原因是, redis template向redis存放使用java對象序列化的值,序列化方式和string的一般方式不同,需要的朋友可以參考下2023-08-08
淺談spring-boot 允許接口跨域并實(shí)現(xiàn)攔截(CORS)
本篇文章主要介紹了淺談spring-boot 允許接口跨域并實(shí)現(xiàn)攔截(CORS),具有一定的參考價(jià)值,有興趣的可以了解一下2017-08-08

