Spring Boot - Application Events 的发布顺序_ApplicationStartedEvent

news2024/9/29 11:32:04

文章目录

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

在这里插入图片描述


Pre

Spring Boot - Application Events 的发布顺序_ApplicationEnvironmentPreparedEvent


概述

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

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

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


ApplicationStartedEvent 是Spring Boot中一个重要的应用程序事件,该事件在应用程序的Spring容器刷新之后,但在调用任何应用程序和命令行运行程序之前发布。这个事件的目的是为了允许开发者能够在应用程序启动的过程中执行一些特定的逻辑。

当Spring Boot应用程序启动时,它会经历多个阶段,包括初始化SpringApplicationRunListeners,创建和配置Spring环境,以及刷新ApplicationContext。在ApplicationContext被刷新之后,但尚未调用任何CommandLineRunnerApplicationRunner之前,ApplicationStartedEvent事件被发布。

开发者可以通过实现ApplicationListener接口来监听这个事件。具体来说,他们需要创建一个类,该类实现ApplicationListener接口,并重写onApplicationEvent方法。在这个方法中,开发者可以定义当ApplicationStartedEvent事件被发布时应该执行的逻辑。
此外,Spring Boot还提供了其他几种方式在应用程序启动时执行自定义代码,例如使用CommandLineRunner接口或ApplicationRunner接口。这些接口在ApplicationStartedEvent事件之后被调用,因此也可以用于启动时的逻辑。

总之,ApplicationStartedEvent是Spring Boot中一个关键的应用程序事件,它允许开发者在应用程序启动过程中执行特定的逻辑,从而实现对应用程序启动过程的精细控制。


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
     */
    @Override
    public 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);

       // 在执行 Spring Boot 应用程序时,会调用 的方法 ApplicationStartedListener , onApplicationEvent() 使我们能够在应用程序开始时执行任何必要的附加设置或初始化任务
       springApplication.addListeners(new ApplicationStartedListener());

       springApplication.run(args);
    }


}

方式二: 通过spring.factories 配置

在这里插入图片描述

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

运行日志

在这里插入图片描述


源码分析

首先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应用上下文,初始化为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; // 返回应用上下文
}

我们重点看

listeners.started(context);

继续

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


继续 listener.started(context)

 	@Override
	public void started(ConfigurableApplicationContext context) {
		context.publishEvent(new ApplicationStartedEvent(this.application, this.args, context));
		AvailabilityChangeEvent.publish(context, LivenessState.CORRECT);
	}

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

/**
 * 发布一个事件,这个事件可以被订阅者处理。
 *
 * @param event 事件对象,不能为null
 * @param eventType 事件类型,用于类型匹配和事件处理器的选择
 */
protected void publishEvent(Object event, @Nullable ResolvableType eventType) {
    // 断言事件对象不能为null
    Assert.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;
        }
    }
}

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

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

在这里插入图片描述

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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

FineBI报表页面大屏小屏自适应显示问题

大屏正常显示 显示正常 小屏BI自适应显示 存在遮挡字体情况 小屏浏览器缩放显示 等比缩放后显示正常

[开发语言][c++][python]:C++与Python中的赋值、浅拷贝与深拷贝

C与Python中的赋值、浅拷贝与深拷贝 1. Python中的赋值、浅拷贝、深拷贝2. C中的赋值、浅拷贝、深拷贝2.1 概念2.2 示例&#xff1a;从例子中理解1) 不可变对象的赋值、深拷贝、浅拷贝2) 可变对象的赋值、浅拷贝与深拷贝3) **可变对象深浅拷贝(外层、内层改变元素)** 写在前面&…

Ubuntu server配置ssh远程登录

使用如下命令进行安装 apt-get install ssh 安装好后启动 service ssh start 然后查看运行状态 然后用本机ping虚拟机 关闭本机和虚拟机防火墙 ufw disable 然后打开Xshell进行连接

删除的数据恢复

1回收站恢复 1.1回收站删除 新手删除是通过del键或者鼠标右键删除,这种删除是并不是真正的删除,而是放到了回收站 1.2回收站的数据恢复 回收站的数据,你要恢复那个直接右键还原即可,删除到回收站的数据并不能称得上是删除,回收站的本质也是一个文件夹,只不过是个特殊的文件…

少儿编程 2023年12月电子学会图形化编程等级考试Scratch二级真题解析(判断题)

2023年12月scratch编程等级考试二级真题 判断题(共10题,每题2分,共20分) 26、声音Medieval1的长度是9.68秒,运行下列程序1或程序2都能实现,播放声音2秒后,声音停止角色移动100步 答案:对 考点分析:考查积木综合使用,重点考查声音积木的使用 程序1中用的是等待播完…

系统存储架构升级分享 | 京东云技术团队

一、业务背景 系统业务功能&#xff1a;系统内部进行数据处理及整合, 对外部系统提供结果数据的初始化(写)及查询数据结果服务。 系统网络架构: 部署架构对切量上线的影响 - 内部管理系统上线对其他系统的读业务无影响分布式缓存可进行单独扩容, 与存储及查询功能升级无关通过…

掌握 Vue 响应式系统,让数据驱动视图(下)

&#x1f90d; 前端开发工程师&#xff08;主业&#xff09;、技术博主&#xff08;副业&#xff09;、已过CET6 &#x1f368; 阿珊和她的猫_CSDN个人主页 &#x1f560; 牛客高级专题作者、在牛客打造高质量专栏《前端面试必备》 &#x1f35a; 蓝桥云课签约作者、已在蓝桥云…

分析一个项目(微信小程序篇)三

目录 接下来分析接口方面&#xff1a; home接口&#xff1a; categories接口&#xff1a; details接口&#xff1a; login接口&#xff1a; 分析一个项目讲究的是如何进行对项目的解析分解&#xff0c;进一步了解项目的整体结构&#xff0c;熟悉项目的结构&#xff0c;能够…

impala元数据自动刷新

一.操作步骤 进入CM界面 > Hive > 配置 > 搜索 启用数据库中的存储通知(英文界面搜索&#xff1a;Enable Stored Notifications in Database)&#xff0c;并且勾选&#xff0c;注意一定要勾选&#xff0c;配置后面的配置不生效。数据库通知的保留时间默认为2天&#…

2-认识小程序项目

基本结构 myapp├─miniprogram┊ └──pages┊ ┊ └──index┊ ┊ ┊ ├──index.json┊ ┊ ┊ ├──index.ts┊ ┊ ┊ ├──index.wxml┊ ┊ ┊ └──index.wxss┊ ┊ └──logs┊ ┊ ├──index.json┊ ┊ ├──index.ts┊ ┊ ├…

评论转换输出 - 华为OD统一考试

OD统一考试 分值&#xff1a; 200分 题解&#xff1a; Java / Python / C 题目描述 在一个博客网站上&#xff0c;每篇博客都有评论。每一条评论都是一个非空英文字母字符串。 评论具有树状结构&#xff0c;除了根评论外&#xff0c;每个评论都有一个父评论。当评论保存时&am…

VMware workstation安装MX-23.1虚拟机并配置网络

VMware workstation安装MX-23.1虚拟机并配置网络 MX Linux是基于Debian稳定分支的面向桌面的Linux发行&#xff0c;采用Xfce作为缺省桌面&#xff0c;是一份中量级操作系统。该文档适用于在VMware workstation平台安装MX-23.1虚拟机。 1.安装准备 1.1安装平台 Windows 11 …

个人网站制作 Part 3 用JS添加高级交互(表单验证、动态内容更新) | Web开发项目

文章目录 &#x1f469;‍&#x1f4bb; 基础Web开发练手项目系列&#xff1a;个人网站制作&#x1f680; 使用JavaScript进行交互&#x1f528;表单验证&#x1f527;步骤 1: 添加JavaScript文件&#x1f527;步骤 2: 更新表单HTML &#x1f528;动态内容更新&#x1f527;步骤…

用js做个转盘

样式 <style>.wheel {position: relative;width: 400px;height: 400px;border: 1px solid black;border-radius: 50%;overflow: hidden;margin: auto;}.slice {position: absolute;left: 0;top: 0;width: 0;height: 0;border: 200px solid red;/* border-width: 100px 10…

Python - 操作 docx

文章目录 使用库 : python-docx 官方文档&#xff1a;https://python-docx.readthedocs.io 安装 pip install python-docx提取 docx from docx import Documentdoc Document(file_path) text "" for para in doc.paragraphs:text para.text "\n"创建…

小程序系列-5.WXML 模板语法

一、数据绑定 1、在 data 中定义页面的数据 动态绑定内容&#xff1a; 动态绑定属性&#xff1a; 2. Mustache 语法的格式 3. Mustache 语法的应用场景 4. 三元运算 5.算数运算 二、 事件绑定 1. 什么是事件&#xff1f; 2. 小程序中常用的事件 3. 事件对象的属性列表 4.…

【漏洞复现】Office365-Indexs-任意文件读取

漏洞描述 Office 365 Indexs接口存在一个任意文件读取漏洞,攻击者可以通过构造精心设计的请求,成功利用漏洞读取服务器上的任意文件,包括敏感系统文件和应用程序配置文件等。通过利用此漏洞,攻击者可能获得系统内的敏感信息,导致潜在的信息泄露风险 免责声明 技术文章…

高质量训练数据助力大语言模型摆脱数据困境 | 景联文科技

目前&#xff0c;大语言模型的发展已经取得了显著的成果&#xff0c;如OpenAI的GPT系列模型、谷歌的BERT模型、百度的文心一言模型等。这些模型在文本生成、问答系统、对话生成、情感分析、摘要生成等方面都表现出了强大的能力&#xff0c;为自然语言处理领域带来了新的突破。 …

准备好迎接新兴的汽车雷达卫星架构了吗?(TI文档)

引言 随着全球新车评估计划的安全等级和法规对主动安全功能的要求越来越严格&#xff0c;安全是当今车辆的一个不容置疑的特征。全球汽车制造商正在满足这些安全要求&#xff0c;并通过不断增强车辆内的高级驾驶辅助系统(ADAS)功能&#xff0c;包括自动紧急制动(AEB)、自适应巡…

c++例题2点和直线关系

#include<iostream> #include<string> using namespace std; //圆的类 class yuan{ public:int x2 10;int y2 10;int r 5; }; //点的类 class dian{ public :void setx(int x){x1 x;}int getx(){return x1;}void sety(int y){y1 y;}int gety(){return y1;} pr…