聊聊springboot的启动事件

本文主要研究一下springboot的启动事件

SpringApplicationEvent

org/springframework/boot/context/event/SpringApplicationEvent.java

public abstract class SpringApplicationEvent extends ApplicationEvent {private final String[] args;public SpringApplicationEvent(SpringApplication application, String[] args) {super(application);this.args = args;}public SpringApplication getSpringApplication() {return (SpringApplication) getSource();}public final String[] getArgs() {return this.args;}}

SpringApplicationEvent继承了ApplicationEvent,它有几个子类分表是ApplicationStartingEvent、ApplicationEnvironmentPreparedEvent、ApplicationContextInitializedEvent、ApplicationPreparedEvent、ApplicationStartedEvent、ApplicationReadyEvent,期间有异常则抛出ApplicationFailedEvent

SpringApplication.run

org/springframework/boot/SpringApplication.java

	public ConfigurableApplicationContext run(String... args) {StopWatch stopWatch = new StopWatch();stopWatch.start();ConfigurableApplicationContext context = null;Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();configureHeadlessProperty();SpringApplicationRunListeners listeners = getRunListeners(args);listeners.starting();try {ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);configureIgnoreBeanInfo(environment);Banner printedBanner = printBanner(environment);context = createApplicationContext();exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,new Class[] { ConfigurableApplicationContext.class }, context);prepareContext(context, environment, listeners, applicationArguments, printedBanner);refreshContext(context);afterRefresh(context, applicationArguments);stopWatch.stop();if (this.logStartupInfo) {new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);}listeners.started(context);callRunners(context, applicationArguments);}catch (Throwable ex) {handleRunFailure(context, ex, exceptionReporters, listeners);throw new IllegalStateException(ex);}try {listeners.running(context);}catch (Throwable ex) {handleRunFailure(context, ex, exceptionReporters, null);throw new IllegalStateException(ex);}return context;}

SpringApplication的run方法,先触发listeners.starting(),然后执行了prepareEnvironment,之后createApplicationContext,再进行prepareContext和refreshContext,最后触发listeners.started(context),之后执行callRunners,最后触发listeners.running(context),如有异常则会执行handleRunFailure

prepareEnvironment

	private ConfigurableEnvironment prepareEnvironment(SpringApplicationRunListeners listeners,ApplicationArguments applicationArguments) {// Create and configure the environmentConfigurableEnvironment environment = getOrCreateEnvironment();configureEnvironment(environment, applicationArguments.getSourceArgs());ConfigurationPropertySources.attach(environment);listeners.environmentPrepared(environment);bindToSpringApplication(environment);if (!this.isCustomEnvironment) {environment = new EnvironmentConverter(getClassLoader()).convertEnvironmentIfNecessary(environment,deduceEnvironmentClass());}ConfigurationPropertySources.attach(environment);return environment;}

prepareEnvironment会触发listeners.environmentPrepared(environment),即发布ApplicationEnvironmentPreparedEvent

prepareContext

	private void prepareContext(ConfigurableApplicationContext context, ConfigurableEnvironment environment,SpringApplicationRunListeners listeners, ApplicationArguments applicationArguments, Banner printedBanner) {context.setEnvironment(environment);postProcessApplicationContext(context);applyInitializers(context);listeners.contextPrepared(context);if (this.logStartupInfo) {logStartupInfo(context.getParent() == null);logStartupProfileInfo(context);}// Add boot specific singleton beansConfigurableListableBeanFactory beanFactory = context.getBeanFactory();beanFactory.registerSingleton("springApplicationArguments", applicationArguments);if (printedBanner != null) {beanFactory.registerSingleton("springBootBanner", printedBanner);}if (beanFactory instanceof DefaultListableBeanFactory) {((DefaultListableBeanFactory) beanFactory).setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);}if (this.lazyInitialization) {context.addBeanFactoryPostProcessor(new LazyInitializationBeanFactoryPostProcessor());}// Load the sourcesSet<Object> sources = getAllSources();Assert.notEmpty(sources, "Sources must not be empty");load(context, sources.toArray(new Object[0]));listeners.contextLoaded(context);}

prepareContext会触发listeners.contextPrepared(context),即发布ApplicationContextInitializedEvent,执行完成之后触发listeners.contextLoaded(context),即发布ApplicationPreparedEvent

refreshContext

	private void refreshContext(ConfigurableApplicationContext context) {refresh(context);if (this.registerShutdownHook) {try {context.registerShutdownHook();}catch (AccessControlException ex) {// Not allowed in some environments.}}}protected void refresh(ApplicationContext applicationContext) {Assert.isInstanceOf(AbstractApplicationContext.class, applicationContext);((AbstractApplicationContext) applicationContext).refresh();}	

refreshContext会执行refresh方法

org/springframework/context/support/AbstractApplicationContext.java

	public void refresh() throws BeansException, IllegalStateException {synchronized (this.startupShutdownMonitor) {// Prepare this context for refreshing.prepareRefresh();// Tell the subclass to refresh the internal bean factory.ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();// Prepare the bean factory for use in this context.prepareBeanFactory(beanFactory);try {// Allows post-processing of the bean factory in context subclasses.postProcessBeanFactory(beanFactory);// Invoke factory processors registered as beans in the context.invokeBeanFactoryPostProcessors(beanFactory);// Register bean processors that intercept bean creation.registerBeanPostProcessors(beanFactory);// Initialize message source for this context.initMessageSource();// Initialize event multicaster for this context.initApplicationEventMulticaster();// Initialize other special beans in specific context subclasses.onRefresh();// Check for listener beans and register them.registerListeners();// Instantiate all remaining (non-lazy-init) singletons.finishBeanFactoryInitialization(beanFactory);// Last step: publish corresponding event.finishRefresh();}catch (BeansException ex) {if (logger.isWarnEnabled()) {logger.warn("Exception encountered during context initialization - " +"cancelling refresh attempt: " + ex);}// Destroy already created singletons to avoid dangling resources.destroyBeans();// Reset 'active' flag.cancelRefresh(ex);// Propagate exception to caller.throw ex;}finally {// Reset common introspection caches in Spring's core, since we// might not ever need metadata for singleton beans anymore...resetCommonCaches();}}}

refresh先执行postProcessBeanFactory,比如添加BeanPostProcessors,之后执行invokeBeanFactoryPostProcessors,即执行BeanFactoryPostProcessor的postProcessBeanFactory方法
refresh执行完之后触发listeners.started(context)即发布ApplicationStartedEvent
执行完callRunners之后触发listeners.running(context)即发布ApplicationReadyEvent

handleRunFailure

	private void handleRunFailure(ConfigurableApplicationContext context, Throwable exception,Collection<SpringBootExceptionReporter> exceptionReporters, SpringApplicationRunListeners listeners) {try {try {handleExitCode(context, exception);if (listeners != null) {listeners.failed(context, exception);}}finally {reportFailure(exceptionReporters, exception);if (context != null) {context.close();}}}catch (Exception ex) {logger.warn("Unable to close ApplicationContext", ex);}ReflectionUtils.rethrowRuntimeException(exception);}

触发listeners.failed(context, exception)即发布ApplicationFailedEvent

小结

SpringApplication的run方法,先触发listeners.starting()(ApplicationStartingEvent),然后执行了prepareEnvironment(ApplicationEnvironmentPreparedEvent),之后createApplicationContext,再进行prepareContext和refreshContext(ApplicationContextInitializedEvent–>ApplicationPreparedEvent),最后触发listeners.started(context)(ApplicationStartedEvent),之后执行callRunners,最后触发listeners.running(context)(ApplicationReadyEvent),期间有异常会执行handleRunFailure,触发listeners.failed(context, exception)(ApplicationFailedEvent)

其中refresh的时候会执行BeanFactoryPostProcessor的postProcessBeanFactory方法
整体顺序如下:ApplicationStartingEvent --> ApplicationEnvironmentPreparedEvent --> ApplicationContextInitializedEvent --> ApplicationPreparedEvent --> ApplicationStartedEvent --> ApplicationReadyEvent,期间有异常则抛出ApplicationFailedEvent

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

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

相关文章

Cesium 使用 Entity 绘制点线面

文章目录 一、绘制点1. 第一种2. 第二种 二、绘制面三、绘制线四、移除 Entity <!--* Author: HuKang* Date: 2023-08-18 11:06:43* LastEditTime: 2023-08-25 09:16:59* LastEditors: HuKang* Description: program-c* FilePath: \global-data-display\src\views\program-c…

机器学习笔记之优化算法(十七)梯度下降法在强凸函数的收敛性分析

机器学习笔记之优化算法——梯度下降法在强凸函数的收敛性分析 引言回顾&#xff1a;梯度下降法在强凸函数的收敛性二阶可微——梯度下降法在强凸函数的收敛性推论 引言 上一节介绍并证明了&#xff1a;梯度下降法在强凸函数上的收敛速度满足 Q \mathcal Q Q-线性收敛。 本节将…

Postgresql12基于时间点恢复

1、环境 centos 7系统 postgresql 12 docker 20.10.6 2、整体思路 1&#xff09;进行一个pgdata目录的全量备份 2&#xff09;通过wal日志恢复到故障发生之前某个时间点 3、操作步骤 配置postgresql.conf文件 #日志级别 wal_level replica #归档开关 archive_mode on …

第一讲使用IDEA创建Java工程——HelloWorld

一、前言导读 为了能够让初学者更快上手Java,不会像其他书籍或者视频一样,介绍一大堆历史背景,默认大家已经知道Java这么编程语言了。本专栏只会讲解干货,直接从HelloWord入手,慢慢由浅入深,讲个各个知识点,这些知识点也是目前工作中项目使用的,而不是讲一些老的知识点…

16、Flink 的table api与sql之连接外部系统: 读写外部系统的连接器和格式以及FileSystem示例(1)

Flink 系列文章 1、Flink 部署、概念介绍、source、transformation、sink使用示例、四大基石介绍和示例等系列综合文章链接 13、Flink 的table api与sql的基本概念、通用api介绍及入门示例 14、Flink 的table api与sql之数据类型: 内置数据类型以及它们的属性 15、Flink 的ta…

nvm安装使用教程

文章目录 下载配置安装最新稳定版 node安装指定版本查看版本切换版本删除版本 常见问题安装node后 显示拒绝访问的问题使用cnpm会报错的问题降低cnpm版本npm镜像 下载 NVM for Windows 下载地址&#xff1a;https://link.juejin.cn/?targethttps%3A%2F%2Fgithub.com%2Fcoreyb…

《深度学习计算机视觉 》书籍分享(包邮送书三本)

深度学习计算机视觉介绍 随着计算机技术的发展和进步&#xff0c;计算机视觉领域得到了广泛的关注和研究。而深度学习作为一种强大的机器学习方法&#xff0c;已经成为计算机视觉领域的重要工具之一。本文将介绍深度学习在计算机视觉中的应用和取得的成果。 深度学习是一种模…

Sim/circuit10

通过观察可知&#xff0c;在a、b同时为0或1时&#xff0c;state的值改变 state的值可以改变q的输出&#xff0c;1为ab的同或&#xff0c;0为异或 利用assign q进行输出 module top_module (input clk,input a,input b,output q,output state );always(posedge clk)if(a&…

Go学习-Day2

文章目录 标识符变量基础语法字符串类型类型转换string和其他基本类型转换其他类型转stringstring转其他类型 指针类型运算符标准IO分支语句 个人博客 标识符 驼峰法&#xff0c;首字母大写可以在其他包里使用&#xff0c;首字母小写只能在本包内使用跨包使用&#xff0c;的im…

基于JAVA SpringBoot和UniAPP的宠物服务预约小程序

随着社会的发展和人们生活水平的提高&#xff0c;特别是近年来&#xff0c;宠物快速进入人们的家中&#xff0c;成为人们生活中重要的娱乐内容之一&#xff0c;过去宠物只是贵族的娱乐&#xff0c;至今宠物在中国作为一种生活方式得到了广泛的认可&#xff0c;随着人们精神文明…

前端面试的性能优化部分(12)每天10个小知识点

目录 系列文章目录前端面试的性能优化部分&#xff08;1&#xff09;每天10个小知识点前端面试的性能优化部分&#xff08;2&#xff09;每天10个小知识点前端面试的性能优化部分&#xff08;3&#xff09;每天10个小知识点前端面试的性能优化部分&#xff08;4&#xff09;每天…

Docker拉取并配置Grafana

Linux下安装Docker请参考&#xff1a;Linux安装Docker 安装准备 新建挂载目录 /opt/grafana/data目录&#xff0c;准备用来挂载放置grafana的数据 /opt/grafana/plugins目录&#xff0c;准备用来放置grafana的插件 /opt/grafana/config目录&#xff0c;准备用来挂载放置graf…

正则表达式一小时学完

闯关式学习Regex 正则表达式&#xff0c;我感觉挺不错的&#xff0c;记录一下。 遇到不会的题&#xff0c;可以评论交流。 真的很不错 链接 Regex Learn - Step by step, from zero to advanced.

HTTP原理与实现

一、基本概念 一、基本原理* 1、全称&#xff1a; HyperText Transfer Protocol (超文本传输协议) 2、底层实现协议&#xff1a;建立在 TCP/IP 上的无状态连接。 3、基本作用&#xff1a;用于客户端与服务器之间的通信&#xff0c;规定客户端和服务器之间的通信格式。包括请…

长胜证券:货币政策什么意思?

钱银政策是指国家钱银当局经过调控钱银供给量和利率等手法&#xff0c;以到达操控通货膨胀、坚持经济稳定、促进经济增长等目的的一种宏观经济政策。简而言之&#xff0c;钱银政策便是国家中央银行对钱银供给和利率进行调控的政策。那么具体来说&#xff0c;钱银政策到底有哪些…

自动化部署及监测平台基本架构

声明 本文是学习 政务计算机终端核心配置规范. 而整理的学习笔记,分享出来希望更多人受益,如果存在侵权请及时联系我们 核心配置自动化部署及监测技术要求 自动化部署及监测平台基本架构 对于有一定规模的政务终端核心配置应用&#xff0c;需要配备自动化部署及监测平台&am…

C++编程中的六种内存顺序模型

文章目录 前言为什么要设计内存顺序模型常见的内存顺序模型总结 前言 程序员真是一个活到老学到老的职业&#xff0c;一天不学习就会掉队&#xff0c;『内存顺序模型』对于我来说就是一个新的世界&#xff0c;虽然之前写过多线程的服务器&#xff0c;也处理过死锁和竞态条件等…

linux笔记

1、向某个api地址发送get请求 curl -s -x get http://192.168.0.1:8080/api/vi/groups 2、查看内存消耗最多的前10个进程 ps auxw|head -1;ps auxw|sort -rn -k4|head -10 3、查看系统资源占用情况 top命令&#xff0c;运行之后按c键&#xff0c;可以显示出完整的程序名称 …

Spring Boot简介

文章目录 一、引言1.1 初始化配置1.2 整合第三方框架1.3 后期维护1.4 部署工程1.5 敏捷式开发 二、SpringBoot介绍三、SpringBoot快速入门【重点】3.1 快速构建SpringBoot3.1.1 选择构建项目的类型3.1.2 项目的描述3.1.3 指定SpringBoot版本和需要的依赖3.1.4 导入依赖3.1.5 编…

RabbitMQ死信队列

RabbitMQ死信队列 1、过期时间TTL 过期时间TTL表示可以对消息设置预期的时间&#xff0c;在这个时间内都可以被消费者接收获取&#xff1b;过了之后消息将自动被 删除。RabbitMQ可以对消息和队列设置TTL&#xff0c;目前有两种方法可以设置&#xff1a; 第一种方法是通过队列…