Spring Boot - Application Events 的发布顺序_ApplicationStartingEvent

文章目录

  • 概述
  • Code
  • 源码分析

在这里插入图片描述

概述

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

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

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

Spring Boot中的ApplicationStartingEvent是在应用程序启动的最早阶段触发的事件。它在应用程序上下文完全初始化之前触发,此时应用程序刚刚启动,各种初始化任务(如加载配置文件和设置环境)尚不可用。

通过监听ApplicationStartingEvent,我们可以执行一些预初始化任务,例如更新系统属性、读取外部配置、初始化日志框架等。


Code

在这里插入图片描述

package com.artisan.event;

import org.springframework.boot.context.event.ApplicationStartingEvent;
import org.springframework.context.ApplicationListener;

/**
 * @author 小工匠
 * @version 1.0
 * @mark: show me the code , change the world
 */
public class ApplicationStartingListener implements ApplicationListener<ApplicationStartingEvent> {

    /**
     * ApplicationStartingEvent 在应用程序启动过程的一开始,就在应用程序上下文完全初始化之前触发。
     * 此时,应用程序刚刚启动,加载配置文件、设置环境等各种初始化任务尚不可用。
     * <p>
     * <p>
     * 通过监听 ,我们可以执行预初始化任务 ApplicationStartingEvent ,例如更新系统属性、读取外部配置、初始化日志记录框架等
     * <p>
     * <p>
     * 为了处理 ApplicationStartingEvent ,我们可以通过实现 ApplicationListener 作为 ApplicationStartingEvent 泛型类型的接口来创建一个自定义事件侦听器。
     * 此侦听器可以在主应用程序类中手动注册
     *
     * @param event the event to respond to
     */
    @Override
    public void onApplicationEvent(ApplicationStartingEvent event) {
        System.out.println("--------------------> Handling ApplicationStartingEvent 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);

        // 当应用程序运行时,将调用 的方法 ApplicationStartingListener#onApplicationEvent()
        // 允许我们在应用程序上下文完全建立之前执行任何必要的任务。
        springApplication.addListeners(new ApplicationStartingListener());

       springApplication.run(args);
    }


}

方式二: 通过spring.factories 配置

在这里插入图片描述

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

当应用程序运行时,ApplicationStartingListener#onApplicationEvent()方法将被调用,从而允许我们在应用程序上下文完全建立之前执行任何必要的任务

运行日志

在这里插入图片描述


源码分析

首先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));

通过spring.factories 配置的方式会扫描到 然后 setListeners

在这里插入图片描述


run

继续run

// 开始启动Spring应用程序
public ConfigurableApplicationContext run(String... args) {
    StopWatch stopWatch = new StopWatch(); // 创建一个计时器
    stopWatch.start(); // 开始计时
    
    DefaultBootstrapContext bootstrapContext = createBootstrapContext(); // 创建引导上下文
    ConfigurableApplicationContext context = null; // Spring应用上下文,初始化为null
    
    configureHeadlessProperty(); // 配置无头属性(如:是否在浏览器中运行)

    SpringApplicationRunListeners listeners = getRunListeners(args); // 获取运行监听器
    listeners.starting(bootstrapContext, this.mainApplicationClass); // 通知监听器启动过程开始
    
    try {
        ApplicationArguments applicationArguments = new DefaultApplicationArguments(args); // 创建应用参数
        ConfigurableEnvironment environment = prepareEnvironment(listeners, bootstrapContext, applicationArguments); // 预备环境
        configureIgnoreBeanInfo(environment); // 配置忽略BeanInfo
        
        Banner printedBanner = printBanner(environment); // 打印Banner
        context = 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; // 返回应用上下文
}

我们重点看

    SpringApplicationRunListeners listeners = getRunListeners(args); // 获取运行监听器
    listeners.starting(bootstrapContext, this.mainApplicationClass); // 通知监听器启动过程开始

在这里插入图片描述

继续查看 starting

// 用于执行与特定步骤相关的监听器和动作。
private void doWithListeners(String stepName, Consumer<SpringApplicationRunListener> listenerAction,
        Consumer<StartupStep> stepAction) {
    // 获取一个StartupStep实例,这个实例对应于指定的stepName。
    StartupStep step = this.applicationStartup.start(stepName);
    // 遍历所有的监听器,并执行动作(这些动作通常是启动监听器)。
    this.listeners.forEach(listenerAction);
    // 如果存在步骤动作(stepAction),则执行它。步骤动作可以用来添加额外的信息或执行额外的逻辑。
    if (stepAction != null) {
        stepAction.accept(step);
    }
    // 完成当前步骤。
    step.end();
}

// 这个方法是在Spring Boot应用启动的时候被调用的。它接收一个可配置的启动上下文和一个主应用类(main class)。
void starting(ConfigurableBootstrapContext bootstrapContext, Class<?> mainApplicationClass) {
    // 使用doWithListeners方法来执行一个动作,这个动作是在spring.boot.application.starting这个阶段执行的。
    // 它会调用所有的SpringApplicationRunListener监听器来完成启动过程。
    doWithListeners("spring.boot.application.starting", (listener) -> listener.starting(bootstrapContext),
            (step) -> {
                // 如果主应用类不为null,给当前步骤添加一个标签,标签的值是主应用类的名字。
                if (mainApplicationClass != null) {
                    step.tag("mainApplicationClass", mainApplicationClass.getName());
                }
            });
}

在这里插入图片描述

在这里插入图片描述

发布事件

	@Override
	public void starting(ConfigurableBootstrapContext bootstrapContext) {
		this.initialMulticaster
				.multicastEvent(new ApplicationStartingEvent(bootstrapContext, this.application, this.args));
	}

继续

	@Override
	public void multicastEvent(ApplicationEvent event) {
		multicastEvent(event, resolveDefaultEventType(event));
	}
@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);
        }
    }
}

继续

private void doInvokeListener(ApplicationListener listener, ApplicationEvent event) {
		try {
			listener.onApplicationEvent(event);
		}
		catch (ClassCastException ex) {
			......
		}
	}

在这里插入图片描述

就到了我们自定义实现的代码逻辑中了。

  @Override
    public void onApplicationEvent(ApplicationStartingEvent event) {
        System.out.println("--------------------> Handling ApplicationStartingEvent here!");
    }

在这里插入图片描述

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

C#上位机与欧姆龙PLC的通信11----【爆肝】上位机应用开发(Winform版)

1、先上图 前面10讲&#xff0c;让你爽煹了肝&#xff0c;已经进入最后收尾阶段&#xff0c;这节来个常规应用&#xff0c;让前面的技能直接飞上天&#xff0c;我们要做的界面软件是这样的&#xff0c;虽然没有潘金莲漂亮&#xff0c;但也是爆抱&#xff1a; 2、如何爆&#x…

win系统搭建Minecraft世界服务器,MC开服教程,小白开服教程

Windows系统搭建我的世界世界服务器&#xff0c;Minecraft开服教程&#xff0c;小白开服教程&#xff0c;MC 1.19.4版本服务器搭建教程。 此教程使用 Mohist 1.19.4 服务端&#xff0c;此服务端支持Forge模组和Bukkit/Spigot/Paper插件&#xff0c;如果需要开其他服务端也可参…

应用在LCD显示器电源插头里的氮化镓(GaN)MTC-65W1C

LCD&#xff08;Liquid Crystal Display&#xff09;显示器是利用液晶显示技术来进行图像表现的显示装置&#xff0c;从液晶显示器的结构来看&#xff0c;无论是笔记本电脑还是桌面系统&#xff0c;采用的LCD显示屏都是由不同部分组成的分层结构。LCD显示器按照控制方式不同可分…

网络编程的理论基础

文章目录 1 重点知识2 应用层3 再谈 "协议"4 HTTP协议4.1 认识URL4.2 urlencode和urldecode4.3 HTTP协议格式4.4 HTTP的方法4.5 HTTP的状态码4.6 HTTP常见Header4.7 最简单的HTTP服务器 3 传输层4 再谈端口号4.1 端口号范围划分4.2 认识知名端口号(Well-Know Port Nu…

2024美赛数学建模思路 - 复盘:光照强度计算的优化模型

文章目录 0 赛题思路1 问题要求2 假设约定3 符号约定4 建立模型5 模型求解6 实现代码 建模资料 0 赛题思路 &#xff08;赛题出来以后第一时间在CSDN分享&#xff09; https://blog.csdn.net/dc_sinor?typeblog 1 问题要求 现在已知一个教室长为15米&#xff0c;宽为12米&…

Linux动态分配IP与正向解析DNS

目录 一、DHCP分配 1. 动态分配 1.1 服务端服务安装 1.2 修改服务端dhcp配置 1.3 修改客户端dhcp&#xff0c;重启查询网卡信息 2. 根据mac固定分配 2.1 修改服务器端dhcp服务配置 2.2 客户端自动获取&#xff0c;查看网卡信息 二、时间同步 1. 手动同步 2. 自动同…

小汪,TCP连接和断连夺命6连问你可能扛得住?

目录 TCP三次握手连接和四次挥手断连的几处疑问 一、建立连接&#xff0c;为什么是三次握手&#xff0c;而不是二次握手&#xff1f; 二、为什么每次建立 TCP 连接时&#xff0c;初始化的序列号都要求不一样呢&#xff1f; 三、断开连接&#xff0c;为什么是四次握手&#x…

【C语言】ipoib驱动 - ipoib_cm_post_receive_srq_rss函数

一、ipoib_cm_post_receive_srq_rss函数定义 static int ipoib_cm_post_receive_srq_rss(struct net_device *dev,int index, int id) {struct ipoib_dev_priv *priv ipoib_priv(dev);struct ipoib_recv_ring *recv_ring priv->recv_ring index;struct ib_sge *sge;stru…

聚乙烯PE的特性有哪些?UV胶水能够粘接聚乙烯PE吗?

聚乙烯&#xff08;Polyethylene&#xff0c;PE&#xff09;是一种聚合物&#xff0c;是由乙烯&#xff08;ethylene&#xff09;单体通过聚合反应形成的合成塑料。以下是聚乙烯的一些主要化学特性&#xff1a; 1.化学式&#xff1a; 聚乙烯的基本化学式是 (C2H4)n&#xff0c;…

Camunda Sub Process

一&#xff1a;内嵌子流程 repositoryService.createDeployment().name("内嵌子流程").addClasspathResource("bpmn/embed_sub_process.bpmn").deploy(); identityService.setAuthenticatedUserId("huihui"); ProcessInstance processInstance …

【已解决】c++如何打印变量的类型

本博文源于笔者正在编写的c代码&#xff0c;在c/c中我们经常用auto去接一个变量&#xff0c;这样我们既可以不用知道变量或函数结果的类型&#xff0c;就可以轻松愉快编码&#xff0c;如果想要知道变量的类型呢&#xff1f;那就需要这样一个函数。 问题再现 想要用函数去打印…

使用numpy处理图片——90度旋转

在《使用numpy处理图片——镜像翻转和旋转》一文中&#xff0c;我们介绍了如何将图片旋转的方法。本文将使用更简单的方法旋转图片90度。 左旋转90度 import numpy as np import PIL.Image as Imagedata np.array(Image.open(the_starry_night.jpg))# left 90 rot90LeftWith…

SQL-条件查询与聚合函数的使用

目录 DQL-条件查询 1.语法 2.条件 常用的比较运算符如下: 常用的逻辑运算符如下: 案例: 聚合函数 1.常见的聚合函数 2.聚合函数的语法 案例&#xff1a; &#x1f389;欢迎您来到我的MySQL基础复习专栏 ☆* o(≧▽≦)o *☆哈喽~我是小小恶斯法克&#x1f379; ✨博客…

pycharm导入etree报Cannot find reference ‘etree‘ in ‘__init__.py‘ more... (Ctrl+F1)

问题 发现 from lxml import etree的时候&#xff0c;etree报错了。提示Cannot find reference etree in __init__.py more... (CtrlF1)。 解决办法 后面发现是pycharm自己的BUG&#xff0c;所以写了新的写法

turnjs实现翻书效果

需求&#xff1a;要做一个效果&#xff0c;类似于阅读器上的翻书效果。 咱们要实现这个需求就需要使用turnjs这个插件&#xff0c;他的官网是turnjs官网。 进入官网后可以点击 这个按钮去下载官网的demo。 这个插件依赖于jQuery&#xff0c;所以你的先安装jQuery. npm insta…

SwiftUI之深入解析Frame Behaviors

一、Frame 简介 当开始使用 SwiftUI 时&#xff0c;可能接触到的第一个修饰符是 frame(width:height:alignment)&#xff0c;定义 frame 是 SwiftUI 最具挑战性的任务之一&#xff0c;当我们使用修饰符&#xff08;如 .frame().&#xff09;时&#xff0c;会发生很多事情。Swi…

抵御爬虫的前线护盾:深度解读验证码技术的演变历程

一.前言 在当今信息技术迅速发展的背景下&#xff0c;网站和在线服务面临着日益增长的自动化访问威胁&#xff0c;这些大多来自于各类爬虫程序。这种大量的自动化访问不仅对网站的正常运行构成压力&#xff0c;还可能导致敏感数据的泄露&#xff0c;甚至被用于不正当竞争和恶意…

小议CompletableFuture 链式执行和响应式编程

相关文章&#xff1a; 用最简单的方式理解同步和异步、阻塞与非阻塞CompletableFuture 实战 背景 昨晚和一个朋友讨论了他在开发过程中遇到的一个场景设计问题。这个场景可以简化为&#xff1a;服务接收到一个需要处理的任务请求&#xff0c;然后立即返回。这个任务需要经过…

【Oracle】数据库查询与SQL语句

Oracle查询 一、单表查询 1、简单条件查询 1&#xff09;精确查询 SELECT* FROMT_OWNERS WHEREwatermeter 304082&#xff09;模糊查询 SELECT* FROMt_owners WHEREname LIKE %刘%3&#xff09;and运算符 SELECT* FROMt_owners WHEREname LIKE %刘% AND housenumb…

梦想贩卖机升级版知识付费源码,包含前后端源码,非线传,修复最新登录接口问题

梦想贩卖机升级版&#xff0c;变现宝吸收了资源变现类产品的许多优势&#xff0c;并剔除了那些无关紧要的元素&#xff0c;使得本产品在运营和变现能力方面实现了质的飞跃。多领域素材资源知识变现营销裂变独立版本。 支持&#xff1a;视频、音频、图文、文档、会员、社群、用…
最新文章