您的位置:首頁技術文章
文章詳情頁

SpringBoot加載應用事件監聽器代碼實例

瀏覽:2日期:2023-05-14 10:58:30

利用 Spring 工廠加載機制,實例化 ApplicationListener 實現類,并排序對象集合

創建應用事件監聽器

創建類實現接口ApplicationListener,可以使用@Order或實現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中配置

# ApplicationListenerorg.springframework.context.ApplicationListener=com.imooc.diveinspringboot.listener.AfterHelloWorldApplicationListener,com.imooc.diveinspringboot.listener.HelloWorldApplicationListener,

輸出

HelloWorld : application , timestamp : 1591105193644AfterHelloWorld : application , timestamp : 1591105193644

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。

標簽: Spring
相關文章:
国产综合久久一区二区三区