Spring ApplicationListener的使用詳解
介紹
Spring ApplicationListener 是Spring事件機制的一部分,與ApplicationEvent抽象類結(jié)合完成ApplicationContext的事件通知機制.
ContextRefreshedEvent事件監(jiān)聽
以Spring的內(nèi)置事件ContextRefreshedEvent為例,當ApplicationContext被初始化或刷新時,會觸發(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 方法省略
}
//實現(xiàn)ApplicationListener接口
@Component
public 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, "十二點了 該吃飯了~");
applicationContext.publishEvent(myEvent);
// System.out.println("發(fā)送結(jié)束");
}
}
結(jié)果

到此這篇關(guān)于Spring ApplicationListener的使用詳解的文章就介紹到這了,更多相關(guān)Spring ApplicationListener 內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Spring ApplicationListener監(jiān)聽器用法詳解
- Spring ApplicationListener源碼解析
- SpringBoot中ApplicationEvent和ApplicationListener用法小結(jié)
- SpringBoot ApplicationListener事件監(jiān)聽接口使用問題探究
- Spring事件監(jiān)聽器ApplicationListener源碼詳解
- SpringBoot中的ApplicationListener事件監(jiān)聽器使用詳解
- Spring中ApplicationListener的使用解析
- spring中ApplicationListener的使用小結(jié)
相關(guān)文章
在Spring-Boot中如何使用@Value注解注入集合類
這篇文章主要介紹了在Spring-Boot中如何使用@Value注解注入集合類的操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-08-08
Java基于ReadWriteLock實現(xiàn)鎖的應(yīng)用
這篇文章主要介紹了Java基于ReadWriteLock實現(xiàn)鎖的應(yīng)用,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-10-10
Java?深入理解創(chuàng)建型設(shè)計模式之建造者模式
建造者(Builder)模式和工廠模式的關(guān)注點不同:建造者模式注重零部件的組裝過程,而工廠方法模式更注重零部件的創(chuàng)建過程,但兩者可以結(jié)合使用2022-02-02

