详解SpringBoot加载应用事件监听器

发布时间:2020-07-18 10:54:36 作者:小猪
来源:亿速云 阅读:222

小编这次要给大家分享的是详解SpringBoot加载应用事件监听器,文章内容丰富,感兴趣的小伙伴可以来了解一下,希望大家阅读完这篇文章之后能够有所收获。

利用 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中配置

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

输出

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

看完这篇关于详解SpringBoot加载应用事件监听器的文章,如果觉得文章内容写得不错的话,可以把它分享出去给更多人看到。

推荐阅读:
  1. SpringBoot 教程之属性加载详解
  2. SpringBoot2 整合Kafka组件,应用案例和流程详解

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

spring boot

上一篇:Android游戏开发十日通(6)- 太空大战

下一篇:ELK日志分析系统搭建配置

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》