SpringBoot2.0 监听器ApplicationListener的使用-监听ApplicationReadyEvent事件

本文介绍了如何在SpringBoot项目中使用监听器实现项目启动后的特定操作。具体包括定义监听器类并实现ApplicationListener接口的方法,以及如何通过SpringApplication的addListeners方法注册自定义监听器。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参考: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);
    
    }
}

启动项目

 

转载于:https://www.cnblogs.com/JoeyWong/p/9050189.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值