spring boot 事件机制

概述

spring boot 版本为 2.7.17

整体看一下springspring boot 相关事件。
在这里插入图片描述

根据下文所给的源码关键处,打上断点,可以进行快速调试。降低源码阅读难度。

实践

spring 相关事件

  • 上下文更新事件(ContextRefreshedEvent):该事件会在ApplicationContext更新时发布。也可以在调用ConfigurableApplicationContext接口中的refresh()方法时被触发。
  • 上下文开始事件(ContextStartedEvent):当容器ConfigurableApplicationContext的Start()方法开始/重新开始容器时触发该事件。
  • 上下文停止事件(ContextStoppedEvent):当容ConfigurableApplicationContext的Stop()方法停止容器时触发该事件。
  • 上下文关闭事件(ContextClosedEvent):当ApplicationContext被关闭时触发该事件。容器被关闭时,其管理的所有单例Bean都被销毁。

spring boot 相关事件

  • ApplicationStartingEvent :spring boot启动开始时执行的事件
  • ApplicationEnvironmentPreparedEvent:spring boot 对应Enviroment已经准备完毕,但此时上下文context还没有创建。
  • ApplicationPreparedEvent:spring boot上下文context创建完成,但此时spring中的bean是没有完全加载完成的(org.springframework.boot.SpringApplicationRunListeners#environmentPrepared 这个触发加载配置文件)。
  • ApplicationFailedEvent:spring boot启动异常时执行事件

监听spring boot ready事件

代码

@Component
public class SpringBootReadyListener implements ApplicationListener<ApplicationReadyEvent> {

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        System.out.println("....ready..");
    }
}

窗口执行结果
在这里插入图片描述

源码

初始化流程

org.springframework.boot.SpringApplicationRunListener 很重要的接口,后面spring boot 发事件消息,使用这个接口的实现类 org.springframework.boot.context.event.EventPublishingRunListener 来执行。

org.springframework.boot.SpringApplication#getRunListeners

在这里插入图片描述

调用流程

org.springframework.boot.SpringApplication#run(java.lang.Class<?>[], java.lang.String[])
org.springframework.boot.SpringApplication#run(java.lang.String...)
org.springframework.boot.SpringApplicationRunListeners#ready
org.springframework.boot.SpringApplicationRunListeners#doWithListeners(java.lang.String, java.util.function.Consumer<org.springframework.boot.SpringApplicationRunListener>, java.util.function.Consumer<org.springframework.core.metrics.StartupStep>)
org.springframework.boot.context.event.EventPublishingRunListener#ready
org.springframework.context.support.AbstractApplicationContext#publishEvent(java.lang.Object, org.springframework.core.ResolvableType)
org.springframework.context.support.AbstractApplicationContext#getApplicationEventMulticaster
org.springframework.context.event.SimpleApplicationEventMulticaster#invokeListener
org.springframework.context.event.SimpleApplicationEventMulticaster#doInvokeListener

在这里插入图片描述

发送启动 ready 事件消息。
在这里插入图片描述
在这里插入图片描述

执行结束
在这里插入图片描述

结束

根据上文所给的源码关键处,打上断点,可以进行快速调试。降低源码阅读难度。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

流月up

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值