歡迎您光臨本站 註冊首頁

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

←手機掃碼閱讀     zhang3221994 @ 2020-06-08 , reply:0

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

創建應用事件監聽器
 

創建類實現接口ApplicationListener,可以使用@Order或實現Orderd接口進行排序
 

  @Order(Ordered.HIGHEST_PRECEDENCE)  public class HelloWorldApplicationListener implements ApplicationListener{    @Override    public void onApplicationEvent(ContextRefreshedEvent event) {      System.out.println("HelloWorld : " + event.getApplicationContext().getId()          + " , timestamp : " + event.getTimestamp());    }  }

 

  public class AfterHelloWorldApplicationListener implements ApplicationListener,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


[zhang3221994 ] SpringBoot加載應用事件監聽器代碼實例已經有221次圍觀

http://coctec.com/docs/java/show-post-237457.html