百度360必应搜狗淘宝本站头条
当前位置:网站首页 > IT技术 > 正文

SpringBoot 启动过程(springboot启动过程中执行自定义代码)

wptr33 2025-06-10 02:11 4 浏览

在看源码的过程中,我们会看到以下四个类的方法经常会被调用,我们需要对一下几个类有点印象:

  • ApplicationContextInitializer
  • ApplicationRunner
  • CommandLineRunner
  • SpringApplicationRunListener

下面开始源码分析,先从 SpringBoot 的启动类的 run() 方法开始看,以下是调用链:SpringApplication.run() -> run(new Class[]{primarySource}, args) -> new SpringApplication(primarySources)).run(args)。

一直在run,终于到重点了,我们直接看 new SpringApplication(primarySources)).run(args) 这个方法。

上面的方法主要包括两大步骤:

  • 创建 SpringApplication 对象。
  • 运行 run() 方法。

创建 SpringApplication 对象

Bash
public SpringApplication(ResourceLoader resourceLoader, Class... primarySources) { 
    
    this.sources = new LinkedHashSet(); 
    this.bannerMode = Mode.CONSOLE; 
    this.logStartupInfo = true; 
    this.addCommandLineProperties = true; 
    this.addConversionService = true; 
    this.headless = true; 
    this.registerShutdownHook = true; 
    this.additionalProfiles = new HashSet(); 
    this.isCustomEnvironment = false; 
    this.resourceLoader = resourceLoader; 
    Assert.notNull(primarySources, "PrimarySources must not be null"); 
    // 保存主配置类(这里是一个数组,说明可以有多个主配置类) 
    this.primarySources = new LinkedHashSet(Arrays.asList(primarySources)); 
    // 判断当前是否是一个 Web 应用 
    this.webApplicationType = WebApplicationType.deduceFromClasspath(); 
    // 从类路径下找到 META/INF/Spring.factories 配置的所有 ApplicationContextInitializer,然后保存起来 
    this.setInitializers(this.getSpringFactoriesInstances(ApplicationContextInitializer.class)); 
    // 从类路径下找到 META/INF/Spring.factories 配置的所有 ApplicationListener,然后保存起来 
    this.setListeners(this.getSpringFactoriesInstances(ApplicationListener.class)); 
    // 从多个配置类中找到有 main 方法的主配置类(只有一个) 
    this.mainApplicationClass = this.deduceMainApplicationClass(); 
    
} 

运行 run() 方法

Bash
public ConfigurableApplicationContext run(String... args) { 
    
    // 创建计时器 
    StopWatch stopWatch = new StopWatch(); 
    stopWatch.start(); 
    // 声明 IOC 容器 
    ConfigurableApplicationContext context = null; 
    Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList(); 
    this.configureHeadlessProperty(); 
    // 从类路径下找到 META/INF/Spring.factories 获取 SpringApplicationRunListeners 
    SpringApplicationRunListeners listeners = this.getRunListeners(args); 
    // 回调所有 SpringApplicationRunListeners 的 starting() 方法 
    listeners.starting(); 
    Collection exceptionReporters; 
    try { 
    // 封装命令行参数 
    ApplicationArguments applicationArguments = new DefaultApplicationArguments(args); 
    // 准备环境,包括创建环境,创建环境完成后回调 SpringApplicationRunListeners#environmentPrepared()方法,表示环境准备完成 
    ConfigurableEnvironment environment = this.prepareEnvironment(listeners, applicationArguments); 
    this.configureIgnoreBeanInfo(environment); 
    // 打印 Banner 
    Banner printedBanner = this.printBanner(environment); 
    // 创建 IOC 容器(决定创建 web 的 IOC 容器还是普通的 IOC 容器) 
    context = this.createApplicationContext(); 
    exceptionReporters = this.getSpringFactoriesInstances(SpringBootExceptionReporter.class, new Class[]{ConfigurableApplicationContext.class}, context); 
    /*
     * 准备上下文环境,将 environment 保存到 IOC 容器中,并且调用 applyInitializers() 方法
     * applyInitializers() 方法回调之前保存的所有的 ApplicationContextInitializer 的 initialize() 方法
     * 然后回调所有的 SpringApplicationRunListener#contextPrepared() 方法 
     * 最后回调所有的 SpringApplicationRunListener#contextLoaded() 方法 
     */
    this.prepareContext(context, environment, listeners, applicationArguments, printedBanner); 
    // 刷新容器,IOC 容器初始化(如果是 Web 应用还会创建嵌入式的 Tomcat),扫描、创建、加载所有组件的地方 
    this.refreshContext(context); 
    // 从 IOC 容器中获取所有的 ApplicationRunner 和 CommandLineRunner 进行回调 
    this.afterRefresh(context, applicationArguments); 
    stopWatch.stop(); 
    if (this.logStartupInfo) { 
    (new StartupInfoLogger(this.mainApplicationClass)).logStarted(this.getApplicationLog(), stopWatch); 
    } 
    // 调用 所有 SpringApplicationRunListeners#started()方法 
    listeners.started(context); 
    this.callRunners(context, applicationArguments); 
    } catch (Throwable var10) { 
    this.handleRunFailure(context, var10, exceptionReporters, listeners); 
    throw new IllegalStateException(var10); 
    } 
    try { 
    listeners.running(context); 
    return context; 
    } catch (Throwable var9) { 
    this.handleRunFailure(context, var9, exceptionReporters, (SpringApplicationRunListeners)null); 
    throw new IllegalStateException(var9); 
    } 
} 



小结

run() 阶段主要就是回调本节开头提到过的4个监听器中的方法与加载项目中组件到 IOC 容器中,而所有需要回调的监听器都是从类路径下的 META-INF/Spring.factories中获取,从而达到启动前后的各种定制操作

相关推荐

每天一个编程技巧!掌握这7个神技,代码效率飙升200%

“同事6点下班,你却为改BUG加班到凌晨?不是你不努力,而是没掌握‘偷懒’的艺术!本文揭秘谷歌工程师私藏的7个编程神技,每天1分钟,让你的代码从‘能用’变‘逆天’。文末附《Python高效代码模板》,...

Git重置到某个历史节点(Sourcetree工具)

前言Sourcetree回滚提交和重置当前分支到此次提交的区别?回滚提交是指将改动的代码提交到本地仓库,但未推送到远端仓库的时候。...

git工作区、暂存区、本地仓库、远程仓库的区别和联系

很多程序员天天写代码,提交代码,拉取代码,对git操作非常熟练,但是对git的原理并不甚了解,借助豆包AI,写个文章总结一下。Git的四个核心区域(工作区、暂存区、本地仓库、远程仓库)是版本控制的核...

解锁人生新剧本的密钥:学会让往事退场

开篇:敦煌莫高窟的千年启示在莫高窟321窟的《降魔变》壁画前,讲解员指着斑驳色彩说:"画师刻意保留了历代修补痕迹,因为真正的传承不是定格,而是流动。"就像我们的人生剧本,精彩章节永远...

Reset local repository branch to be just like remote repository HEAD

技术背景在使用Git进行版本控制时,有时会遇到本地分支与远程分支不一致的情况。可能是因为误操作、多人协作时远程分支被更新等原因。这时就需要将本地分支重置为与远程分支的...

Git恢复至之前版本(git恢复到pull之前的版本)

让程序回到提交前的样子:两种解决方法:回退(reset)、反做(revert)方法一:gitreset...

如何将文件重置或回退到特定版本(怎么让文件回到初始状态)

技术背景在使用Git进行版本控制时,经常会遇到需要将文件回退到特定版本的情况。可能是因为当前版本出现了错误,或者想要恢复到之前某个稳定的版本。Git提供了多种方式来实现这一需求。...

git如何正确回滚代码(git命令回滚代码)

方法一,删除远程分支再提交①首先两步保证当前工作区是干净的,并且和远程分支代码一致$gitcocurrentBranch$gitpullorigincurrentBranch$gi...

[git]撤销的相关命令:reset、revert、checkout

基本概念如果不清晰上面的四个概念,请查看廖老师的git教程这里我多说几句:最开始我使用git的时候,我并不明白我为什么写完代码要用git的一些列指令把我的修改存起来。后来用多了,也就明白了为什么。gi...

利用shell脚本将Mysql错误日志保存到数据库中

说明:利用shell脚本将MYSQL的错误日志提取并保存到数据库中步骤:1)创建数据库,创建表CreatedatabaseMysqlCenter;UseMysqlCenter;CREATET...

MySQL 9.3 引入增强的JavaScript支持

MySQL,这一广泛采用的开源关系型数据库管理系统(RDBMS),发布了其9.x系列的第三个更新版本——9.3版,带来了多项新功能。...

python 连接 mysql 数据库(python连接MySQL数据库案例)

用PyMySQL包来连接Python和MySQL。在使用前需要先通过pip来安装PyMySQL包:在windows系统中打开cmd,输入pipinstallPyMySQL ...

mysql导入导出命令(mysql 导入命令)

mysql导入导出命令mysqldump命令的输入是在bin目录下.1.导出整个数据库  mysqldump-u用户名-p数据库名>导出的文件名  mysqldump-uw...

MySQL-SQL介绍(mysql sqlyog)

介绍结构化查询语言是高级的非过程化编程语言,允许用户在高层数据结构上工作。它不要求用户指定对数据的存放方法,也不需要用户了解具体的数据存放方式,所以具有完全不同底层结构的不同数据库系统,可以使用相同...

MySQL 误删除数据恢复全攻略:基于 Binlog 的实战指南

在MySQL的世界里,二进制日志(Binlog)就是我们的"时光机"。它默默记录着数据库的每一个重要变更,就像一位忠实的史官,为我们在数据灾难中提供最后的救命稻草。本文将带您深入掌握如...