zoukankan      html  css  js  c++  java
  • SpringBoot2.0 监听器ApplicationListener的使用-监听ApplicationReadyEvent事件

    参考:http://www.shareniu.com/article/73.htm

    一.需求是想将我的写一个方法能在项目启动后就运行,之前使用了redis的消息监听器,感觉可以照着监听器这个思路做,于是想到了sringboot的监听器

    二.目前spring boot中支持的事件类型如下

    1. ApplicationFailedEvent:该事件为spring boot启动失败时的操作

    2. ApplicationPreparedEvent:上下文context准备时触发

    3. ApplicationReadyEvent:上下文已经准备完毕的时候触发

    4. ApplicationStartedEvent:spring boot 启动监听类

    5. SpringApplicationEvent:获取SpringApplication

    6. ApplicationEnvironmentPreparedEvent:环境事先准备

    三.监听器的使用

    第一:首先定义一个自己使用的监听器类并实现ApplicationListener接口。

    @Componen
    public class MessageReceiver implements ApplicationListener<ApplicationReadyEvent> { private Logger logger = LoggerFactory.getLogger(MessageReceiver.class); private UserService userService = null; @Override public void onApplicationEvent(ApplicationReadyEvent event) { ConfigurableApplicationContext applicationContext = event.getApplicationContext();      //解决userService一直为空      userService = applicationContext.getBean(UserService.class);
         System.out.println("name"+userService.getName()); } }

    第二:通过SpringApplication类中的addListeners方法将自定义的监听器注册进去

    public class Application {
        public static void main(String[] args) {
            SpringApplication application = new SpringApplication(Application.class);
            application.addListeners(new MessageReceiver());
            application.run(args);
        
        }
    }

    启动项目

  • 相关阅读:
    POJ 1062 昂贵的聘礼(最短路)题解
    BZOj 墨墨的等式(转化为最短路)题解
    BZOJ 2763 飞行路线(分层图最短路)题解
    HDU 6342 Expression in Memories(模拟)多校题解
    codeforces 543B Destroying Roads
    codeforces 639B Bear and Forgotten Tree 3
    codeforces 645D Robot Rapping Results Report
    codeforces 702E Analysis of Pathes in Functional Graph
    codeforces 721C journey
    codeforces 711D Directed Roads
  • 原文地址:https://www.cnblogs.com/JoeyWong/p/9050189.html
Copyright © 2011-2022 走看看