SpringBoot加載應用事件監(jiān)聽器代碼實例
利用 Spring 工廠加載機制,實例化 ApplicationListener 實現(xiàn)類,并排序對象集合
創(chuàng)建應用事件監(jiān)聽器
創(chuàng)建類實現(xiàn)接口ApplicationListener,可以使用@Order或實現(xiàn)Orderd接口進行排序
@Order(Ordered.HIGHEST_PRECEDENCE)
public class HelloWorldApplicationListener implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
System.out.println("HelloWorld : " + event.getApplicationContext().getId()
+ " , timestamp : " + event.getTimestamp());
}
}
public class AfterHelloWorldApplicationListener implements ApplicationListener<ContextRefreshedEvent>,Ordered {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
System.out.println("AfterHelloWorld : " + event.getApplicationContext().getId()
+ " , timestamp : " + event.getTimestamp());
}
@Override
public int getOrder() {
return Ordered.LOWEST_PRECEDENCE;
}
}
在spring.properties中配置
# ApplicationListener
org.springframework.context.ApplicationListener=\
com.imooc.diveinspringboot.listener.AfterHelloWorldApplicationListener,\
com.imooc.diveinspringboot.listener.HelloWorldApplicationListener,\
輸出
HelloWorld : application , timestamp : 1591105193644
AfterHelloWorld : application , timestamp : 1591105193644
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Spring定時任務只執(zhí)行一次的原因分析與解決方案
在使用Spring的@Scheduled定時任務時,你是否遇到過任務只執(zhí)行一次,后續(xù)不再觸發(fā)的情況?這種情況可能由多種原因導致,如未啟用調(diào)度、線程池問題、異常中斷等,本文將深入分析Spring定時任務只執(zhí)行一次的原因,并提供完整的解決方案,需要的朋友可以參考下2025-03-03
SpringBoot整合SpringSecurity認證與授權
在項目開發(fā)中,權限認證是很重要的,尤其是一些管理類的系統(tǒng),對于權限要求更為嚴格,本文主要介紹了SpringBoot整合SpringSecurity認證與授權,感興趣的可以了解一下2023-11-11

