SpringBoot加載應(yīng)用事件監(jiān)聽器代碼實(shí)例
利用 Spring 工廠加載機(jī)制,實(shí)例化 ApplicationListener 實(shí)現(xiàn)類,并排序?qū)ο蠹?/p>
創(chuàng)建應(yīng)用事件監(jiān)聽器
創(chuàng)建類實(shí)現(xiàn)接口ApplicationListener,可以使用@Order或?qū)崿F(xiàn)Orderd接口進(jìn)行排序
@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
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
