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);
        
        }
    }

    启动项目

  • 相关阅读:
    Ext.js 4.2 默认选中Grid行
    jQuery 中国标准时间转换称yyyy-HH-mm格式
    Ext.js Ext.Container添加垂直滚动
    firefox设置
    linux手机投屏 Scrcpy
    archlinux下nessus安装
    firefox设置
    基于python语言下的UI自动化测试框架搭建(四)
    基于python语言下的UI自动化测试框架搭建(三)
    基于python语言下的UI自动化测试框架搭建(一)
  • 原文地址:https://www.cnblogs.com/JoeyWong/p/9050189.html
Copyright © 2011-2022 走看看