Spring ApplicationListener的使用詳解
介紹
Spring ApplicationListener 是Spring事件機(jī)制的一部分,與ApplicationEvent抽象類結(jié)合完成ApplicationContext的事件通知機(jī)制.
ContextRefreshedEvent事件監(jiān)聽(tīng)
以Spring的內(nèi)置事件ContextRefreshedEvent為例,當(dāng)ApplicationContext被初始化或刷新時(shí),會(huì)觸發(fā)ContextRefreshedEvent事件.如下代碼示例:
@Component public class LearnListener implements ApplicationListener<ContextRefreshedEvent> { @Override public void onApplicationEvent(ContextRefreshedEvent event) { //獲取所有的bean String[] definitionNames = event.getApplicationContext().getBeanDefinitionNames(); for (String name : definitionNames) { //打印名稱 System.out.println("name = " + name); } } }
自定義事件
代碼
//繼承ApplicationEvent 抽象類就可以自定義事件模型 public class MyEvent extends ApplicationEvent { private Long id; private String message; public MyEvent(Object source) { super(source); } public MyEvent(Object source, Long id, String message) { super(source); this.id = id; this.message = message; } //get set 方法省略 }
//實(shí)現(xiàn)ApplicationListener接口 @Component public class MyListener implements ApplicationListener<MyEvent> { @Override public void onApplicationEvent(MyEvent event) { System.out.println("監(jiān)聽(tīng)到事件: "+event.getId()+"\t"+event.getMessage()); } }
測(cè)試
@SpringBootTest @RunWith(SpringRunner.class) public class ListenerTest { @Autowired private ApplicationContext applicationContext; @Test public void testListenner() { MyEvent myEvent = new MyEvent("myEvent", 9527L, "十二點(diǎn)了 該吃飯了~"); applicationContext.publishEvent(myEvent); // System.out.println("發(fā)送結(jié)束"); } }
結(jié)果
到此這篇關(guān)于Spring ApplicationListener的使用詳解的文章就介紹到這了,更多相關(guān)Spring ApplicationListener 內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Spring ApplicationListener監(jiān)聽(tīng)器用法詳解
- Spring ApplicationListener源碼解析
- SpringBoot中ApplicationEvent和ApplicationListener用法小結(jié)
- SpringBoot ApplicationListener事件監(jiān)聽(tīng)接口使用問(wèn)題探究
- Spring事件監(jiān)聽(tīng)器ApplicationListener源碼詳解
- SpringBoot中的ApplicationListener事件監(jiān)聽(tīng)器使用詳解
- Spring中ApplicationListener的使用解析
- spring中ApplicationListener的使用小結(jié)
相關(guān)文章
基于MyBatis的parameterType傳入?yún)?shù)類型
這篇文章主要介紹了基于MyBatis的parameterType傳入?yún)?shù)類型,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-09-09java 將字符串、list 寫入到文件,并讀取內(nèi)容的案例
這篇文章主要介紹了java 將字符串、list 寫入到文件,并讀取內(nèi)容的案例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-09-09Java?Stream比較兩個(gè)List的差異并取出不同的對(duì)象四種方法
今天開發(fā)一個(gè)需求時(shí)要對(duì)A和B兩個(gè)List集合遍歷,并比較出集合A有,而集合B沒(méi)有的值,下面這篇文章主要給大家介紹了關(guān)于Java?Stream比較兩個(gè)List的差異并取出不同對(duì)象的四種方法,需要的朋友可以參考下2024-01-01劍指Offer之Java算法習(xí)題精講N叉樹的遍歷及數(shù)組與字符串
跟著思路走,之后從簡(jiǎn)單題入手,反復(fù)去看,做過(guò)之后可能會(huì)忘記,之后再做一次,記不住就反復(fù)做,反復(fù)尋求思路和規(guī)律,慢慢積累就會(huì)發(fā)現(xiàn)質(zhì)的變化2022-03-03