Spring ApplicationListener的使用詳解
介紹
Spring ApplicationListener 是Spring事件機(jī)制的一部分,與ApplicationEvent抽象類結(jié)合完成ApplicationContext的事件通知機(jī)制.
ContextRefreshedEvent事件監(jiān)聽
以Spring的內(nèi)置事件ContextRefreshedEvent為例,當(dāng)ApplicationContext被初始化或刷新時(shí),會觸發(fā)ContextRefreshedEvent事件.如下代碼示例:
@Componentpublic 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接口 @Componentpublic class MyListener implements ApplicationListener<MyEvent> { @Override public void onApplicationEvent(MyEvent event) { System.out.println('監(jiān)聽到事件: '+event.getId()+'t'+event.getMessage()); }}
測試
@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)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. vue-drag-chart 拖動/縮放圖表組件的實(shí)例代碼2. vue使用moment如何將時(shí)間戳轉(zhuǎn)為標(biāo)準(zhǔn)日期時(shí)間格式3. Android studio 解決logcat無過濾工具欄的操作4. 什么是Python變量作用域5. js select支持手動輸入功能實(shí)現(xiàn)代碼6. PHP正則表達(dá)式函數(shù)preg_replace用法實(shí)例分析7. Android Studio3.6.+ 插件搜索不到終極解決方案(圖文詳解)8. bootstrap select2 動態(tài)從后臺Ajax動態(tài)獲取數(shù)據(jù)的代碼9. Android 實(shí)現(xiàn)徹底退出自己APP 并殺掉所有相關(guān)的進(jìn)程10. 一個(gè) 2 年 Android 開發(fā)者的 18 條忠告
