Spring Boot - Application Events 的发布顺序_ApplicationReadyEvent

文章目录

  • Pre
  • 概述
  • Code
  • 源码分析

在这里插入图片描述


Pre

Spring Boot - Application Events 的发布顺序_ApplicationEnvironmentPreparedEvent


概述

Spring Boot 的广播机制是基于观察者模式实现的,它允许在 Spring 应用程序中发布和监听事件。这种机制的主要目的是为了实现解耦,使得应用程序中的不同组件可以独立地改变和复用逻辑,而无需直接进行通信。

在 Spring Boot 中,事件发布和监听的机制是通过 ApplicationEventApplicationListener 以及事件发布者(ApplicationEventPublisher)来实现的。其中,ApplicationEvent 是所有自定义事件的基础,自定义事件需要继承自它。

ApplicationListener 是监听特定事件并做出响应的接口,开发者可以通过实现该接口来定义自己的监听器。事件发布者(通常由 Spring 的 ApplicationContext 担任)负责发布事件。


ApplicationReadyEvent 是 Spring Boot 中的一个应用事件,表示应用程序已准备好处理请求。这个事件是在应用程序启动后尽可能晚地发布的,以指示应用程序已准备好服务请求。你可以使用这个事件来执行一些初始化后的操作,比如启动后台任务、调度作业、建立与外部系统的连接等。

你可以创建一个自定义事件监听器来处理 ApplicationReadyEvent,并在监听器中执行你需要的操作。下面是一个示例代码:

import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;public class ApplicationReadyListener implements ApplicationListener<ApplicationReadyEvent> {@Overridepublic void onApplicationEvent(ApplicationReadyEvent event) {// 执行应用程序准备好后的操作System.out.println("应用程序已准备好处理请求!");}
}

然后,在你的主应用程序类中注册这个监听器:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class YourApplication {public static void main(String[] args) {SpringApplication app = new SpringApplication(YourApplication.class);app.addListeners(new ApplicationReadyListener());app.run(args);}
}

这样,当应用程序启动后,ApplicationReadyListener 中的 onApplicationEvent 方法将被调用,你可以在这个方法中执行你需要的操作。


在处理 ApplicationReadyEvent 时,你可以使用 @Order 注解来指定操作的顺序和优先级。通过为不同的操作指定不同的顺序值,你可以确保它们按照你期望的顺序执行。

以下是一个示例代码,演示了如何使用 @Order 注解来指定操作的执行顺序:

import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.annotation.Order;@Order(1)
public class FirstApplicationReadyListener implements ApplicationListener<ApplicationReadyEvent> {@Overridepublic void onApplicationEvent(ApplicationReadyEvent event) {// 第一个操作的逻辑}
}@Order(2)
public class SecondApplicationReadyListener implements ApplicationListener<ApplicationReadyEvent> {@Overridepublic void onApplicationEvent(ApplicationReadyEvent event) {// 第二个操作的逻辑}
}

在这个示例中,FirstApplicationReadyListenerSecondApplicationReadyListener 分别使用了 @Order 注解指定了它们的执行顺序。@Order 注解的值越小,优先级越高,因此 FirstApplicationReadyListener 的优先级高于 SecondApplicationReadyListener,它们将按照指定的顺序执行。

通过这种方式,你可以确保 ApplicationReadyEvent 中的操作按照你期望的顺序执行,并且可以保证它们的可靠性。


Code

package com.artisan.event;import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;/*** @author 小工匠* @version 1.0* @mark: show me the code , change the world*/
public class ApplicationStartedListener implements ApplicationListener<ApplicationStartedEvent> {/*** ApplicationStartedEvent 在应用程序启动并执行 main 方法时触发。* 它发生在创建和准备应用程序上下文之后,但在实际执行应用程序 run() 方法之前。* <p>* <p>* 此事件提供了在应用程序启动时执行其他任务或执行自定义逻辑的机会,包括初始化其他组件、设置日志记录、配置动态属性等。* <p>* <p>* 为了处理 ApplicationStartedEvent ,我们可以通过实现 ApplicationStartedEvent 作为泛型类型的 ApplicationListener 接口来创建一个自定义事件侦听器。* 此侦听器可以在主应用程序类中手动注册** @param event the event to respond to*/@Overridepublic void onApplicationEvent(ApplicationStartedEvent event) {System.out.println("--------------------> Handling ApplicationStartedEvent here!");}
}

如何使用呢?

方式一:

@SpringBootApplication
public class LifeCycleApplication {/*** 除了手工add , 在 META-INF下面 的 spring.factories 里增加* org.springframework.context.ApplicationListener=自定义的listener 也可以** @param args*/public static void main(String[] args) {SpringApplication springApplication = new SpringApplication(LifeCycleApplication.class);// 当应用程序完全初始化并准备就绪时,将调用 的方法 ApplicationReadyListener , onApplicationEvent() 从而根据需要执行自定义逻辑springApplication.addListeners(new ApplicationReadyListener());springApplication.run(args);}}

方式二: 通过spring.factories 配置

在这里插入图片描述

org.springframework.context.ApplicationListener=\
com.artisan.event.ApplicationReadyListener

运行日志

在这里插入图片描述


源码分析

首先main方法启动入口

SpringApplication.run(LifeCycleApplication.class, args);

跟进去

public static ConfigurableApplicationContext run(Class<?> primarySource, String... args) {return run(new Class<?>[] { primarySource }, args);}

继续

public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {return new SpringApplication(primarySources).run(args);}

这里首先关注 new SpringApplication(primarySources)

new SpringApplication(primarySources)

	/*** Create a new {@link SpringApplication} instance. The application context will load* beans from the specified primary sources (see {@link SpringApplication class-level}* documentation for details. The instance can be customized before calling* {@link #run(String...)}.* @param resourceLoader the resource loader to use* @param primarySources the primary bean sources* @see #run(Class, String[])* @see #setSources(Set)*/@SuppressWarnings({ "unchecked", "rawtypes" })public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {this.resourceLoader = resourceLoader;Assert.notNull(primarySources, "PrimarySources must not be null");this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));this.webApplicationType = WebApplicationType.deduceFromClasspath();this.bootstrappers = new ArrayList<>(getSpringFactoriesInstances(Bootstrapper.class));setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));this.mainApplicationClass = deduceMainApplicationClass();}

聚焦 setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));


run

继续run

// 开始启动Spring应用程序
public ConfigurableApplicationContext run(String... args) {StopWatch stopWatch = new StopWatch(); // 创建一个计时器stopWatch.start(); // 开始计时DefaultBootstrapContext bootstrapContext = createBootstrapContext(); // 创建引导上下文ConfigurableApplicationContext context = null; // Spring应用上下文,初始化为nullconfigureHeadlessProperty(); // 配置无头属性(如:是否在浏览器中运行)SpringApplicationRunListeners listeners = getRunListeners(args); // 获取运行监听器listeners.starting(bootstrapContext, this.mainApplicationClass); // 通知监听器启动过程开始try {ApplicationArguments applicationArguments = new DefaultApplicationArguments(args); // 创建应用参数ConfigurableEnvironment environment = prepareEnvironment(listeners, bootstrapContext, applicationArguments); // 预备环境configureIgnoreBeanInfo(environment); // 配置忽略BeanInfoBanner printedBanner = printBanner(environment); // 打印Bannercontext = createApplicationContext(); // 创建应用上下文context.setApplicationStartup(this.applicationStartup); // 设置应用启动状态prepareContext(bootstrapContext, context, environment, listeners, applicationArguments, printedBanner); // 准备上下文refreshContext(context); // 刷新上下文,执行Bean的生命周期afterRefresh(context, applicationArguments); // 刷新后的操作stopWatch.stop(); // 停止计时if (this.logStartupInfo) { // 如果需要记录启动信息new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch); // 记录启动信息}listeners.started(context); // 通知监听器启动完成callRunners(context, applicationArguments); // 调用Runner}catch (Throwable ex) {handleRunFailure(context, ex, listeners); // 处理运行失败throw new IllegalStateException(ex); // 抛出异常}try {listeners.running(context); // 通知监听器运行中}catch (Throwable ex) {handleRunFailure(context, ex, null); // 处理运行失败throw new IllegalStateException(ex); // 抛出异常}return context; // 返回应用上下文
}

我们重点看

 listeners.running(context); // 通知监听器运行中

继续

void running(ConfigurableApplicationContext context) {doWithListeners("spring.boot.application.running", (listener) -> listener.running(context));}

继续 listener.running(context)

 @Overridepublic void running(ConfigurableApplicationContext context) {context.publishEvent(new ApplicationReadyEvent(this.application, this.args, context));AvailabilityChangeEvent.publish(context, ReadinessState.ACCEPTING_TRAFFIC);}

继续 context.publishEvent(new ApplicationStartedEvent(this.application, this.args, context));

/*** 发布一个事件,这个事件可以被订阅者处理。** @param event 事件对象,不能为null* @param eventType 事件类型,用于类型匹配和事件处理器的选择*/
protected void publishEvent(Object event, @Nullable ResolvableType eventType) {// 断言事件对象不能为nullAssert.notNull(event, "Event must not be null");// 如果事件本身就是ApplicationEvent的实例,直接使用ApplicationEvent applicationEvent;if (event instanceof ApplicationEvent) {applicationEvent = (ApplicationEvent) event;}// 否则,使用PayloadApplicationEvent进行包装else {applicationEvent = new PayloadApplicationEvent<>(this, event);// 如果事件类型为null,从PayloadApplicationEvent中获取if (eventType == null) {eventType = ((PayloadApplicationEvent<?>) applicationEvent).getResolvableType();}}// 如果有提前注册的事件,直接添加到列表中if (this.earlyApplicationEvents != null) {this.earlyApplicationEvents.add(applicationEvent);}// 否则,使用ApplicationEventMulticaster进行广播else {getApplicationEventMulticaster().multicastEvent(applicationEvent, eventType);}// 如果有父上下文,也发布事件if (this.parent != null) {if (this.parent instanceof AbstractApplicationContext) {((AbstractApplicationContext) this.parent).publishEvent(event, eventType);} else {this.parent.publishEvent(event);}}
}

请关注: getApplicationEventMulticaster().multicastEvent(applicationEvent, eventType);

继续

@Override
public void multicastEvent(final ApplicationEvent event, @Nullable ResolvableType eventType) {// 如果eventType不为null,则直接使用它;否则,使用resolveDefaultEventType方法来解析事件的默认类型。ResolvableType type = (eventType != null ? eventType : resolveDefaultEventType(event));// 获取一个线程池执行器,它用于异步执行监听器调用。Executor executor = getTaskExecutor();// 获取所有对应该事件类型的监听器。for (ApplicationListener<?> listener : getApplicationListeners(event, type)) {// 如果执行器不为null,则使用它来异步执行监听器调用;// 否则,直接同步调用监听器。if (executor != null) {executor.execute(() -> invokeListener(listener, event));}else {invokeListener(listener, event);}}
}

继续

/*** 调用一个事件监听器的方法。** @param listener 要调用的监听器* @param event 要处理的事件*/
private void doInvokeListener(ApplicationListener listener, ApplicationEvent event) {try {// 直接调用监听器的onApplicationEvent方法listener.onApplicationEvent(event);}catch (ClassCastException ex) {String msg = ex.getMessage();// 如果消息为null或者消息匹配事件类的预期类型,则忽略异常并记录debug日志if (msg == null || matchesClassCastMessage(msg, event.getClass())) {Log logger = LogFactory.getLog(getClass());if (logger.isTraceEnabled()) {logger.trace("Non-matching event type for listener: " + listener, ex);}}// 否则,抛出异常else {throw ex;}}
}

继续 就会调到我们自己的业务逻辑了

  @Overridepublic void onApplicationEvent(ApplicationReadyEvent event) {System.out.println("--------------------> Handling ApplicationReadyEvent here!");}

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/345087.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Leetcode10035. 对角线最长的矩形的面积

Every day a Leetcode 题目来源&#xff1a;10035. 对角线最长的矩形的面积 解法1&#xff1a;模拟 给你一个下标从 0 开始的二维整数数组 dimensions。 对于所有下标 i&#xff08;0 < i < dimensions.length&#xff09;&#xff0c;dimensions[i][0] 表示矩形 i …

爬虫实战丨基于requests爬取比特币信息并绘制价格走势图

文章目录 写在前面实验环境实验描述实验内容 写在后面 写在前面 本期内容&#xff1a;基于requests爬取比特币信息并绘制价格走势图 下载地址&#xff1a;https://download.csdn.net/download/m0_68111267/88734451 实验环境 anaconda丨pycharmpython3.11.4requests 安装r…

大模型实战营Day3 基于 InternLM 和 LangChain 搭建你的知识库

LLM的局限性&#xff1a; 知识时效性&#xff0c;专业能力&#xff0c;定制化成本 两种大模型开发范式&#xff1a; RAG FineTune RAG: 检索问答生成 外挂知识库 成本低 FineTune&#xff1a; 更新成本高 GPU算力要求高 RAG开发框图&#xff1a; 用户输入 文本向量化 匹配相似…

Unity 编辑器篇|(四)编辑器拓展GUI类 (全面总结 | 建议收藏)

目录 1. 前言2. 参数2.1 静态变量2.2 静态函数2.3 委托 3. 功能3.1 按钮&#xff1a;Button、RepeatButton3.2 文本&#xff1a;Label 、TextField 、TextArea 、PasswordField3.3 滑动条&#xff1a;HorizontalScrollbar 、VerticalScrollbar3.4 滑条&#xff1a;VerticalSlid…

JVM基础(12)——G1调优

作者简介&#xff1a;大家好&#xff0c;我是smart哥&#xff0c;前中兴通讯、美团架构师&#xff0c;现某互联网公司CTO 联系qq&#xff1a;184480602&#xff0c;加我进群&#xff0c;大家一起学习&#xff0c;一起进步&#xff0c;一起对抗互联网寒冬 学习必须往深处挖&…

pytorch学习笔记(十)

一、损失函数 举个例子 比如说根据Loss提供的信息知道&#xff0c;解答题太弱了&#xff0c;需要多训练训练这个模块。 Loss作用&#xff1a;1.算实际输出和目标之间的差距 2.为我们更新输出提供一定的依据&#xff08;反向传播&#xff09; 看官方文档 每个输入输出相减取…

Handsfree_ros_imu:ROS机器人IMU模块的get_imu_rpy.py文件学习记录

上一篇博客写了关于Handsfree_ros_imu&#xff1a;ROS机器人IMU模块ARHS姿态传感器&#xff08;A9&#xff09;Liunx系统Ubuntu20.04学习启动和运行教程&#xff1a; https://blog.csdn.net/qq_54900679/article/details/135539176?spm1001.2014.3001.5502 这次带来get_imu_r…

C++I/O流——(2)预定义格式的输入/输出(第一节)

归纳编程学习的感悟&#xff0c; 记录奋斗路上的点滴&#xff0c; 希望能帮到一样刻苦的你&#xff01; 如有不足欢迎指正&#xff01; 共同学习交流&#xff01; &#x1f30e;欢迎各位→点赞 &#x1f44d; 收藏⭐ 留言​&#x1f4dd; 含泪播种的人一定能含笑收获&#xff…

【python】08.面向对象编程基础

面向对象编程基础 活在当下的程序员应该都听过"面向对象编程"一词&#xff0c;也经常有人问能不能用一句话解释下什么是"面向对象编程"&#xff0c;我们先来看看比较正式的说法。 "把一组数据结构和处理它们的方法组成对象&#xff08;object&#…

.【机器学习】隐马尔可夫模型(Hidden Markov Model,HMM)

概率图模型是一种用图形表示概率分布和条件依赖关系的数学模型。概率图模型可以分为两大类&#xff1a;有向图模型和无向图模型。有向图模型也叫贝叶斯网络&#xff0c;它用有向无环图表示变量之间的因果关系。无向图模型也叫马尔可夫网络&#xff0c;它用无向图表示变量之间的…

Java 面试题 - 多线程并发篇

线程基础 创建线程有几种方式 继承Thread类 可以创建一个继承自Thread类的子类&#xff0c;并重写其run()方法来定义线程的行为。然后可以通过创建该子类的实例来启动线程。 示例代码&#xff1a; class MyThread extends Thread {public void run() {// 定义线程的行为} …

【python】09.面向对象进阶

面向对象进阶 在前面的章节我们已经了解了面向对象的入门知识&#xff0c;知道了如何定义类&#xff0c;如何创建对象以及如何给对象发消息。为了能够更好的使用面向对象编程思想进行程序开发&#xff0c;我们还需要对Python中的面向对象编程进行更为深入的了解。 property装…