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

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

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

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

  • 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 对象

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() 方法

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中获取,从而达到启动前后的各种定制操作

相关推荐

redis的八种使用场景

前言:redis是我们工作开发中,经常要打交道的,下面对redis的使用场景做总结介绍也是对redis举报的功能做梳理。缓存Redis最常见的用途是作为缓存,用于加速应用程序的响应速度。...

基于Redis的3种分布式ID生成策略

在分布式系统设计中,全局唯一ID是一个基础而关键的组件。随着业务规模扩大和系统架构向微服务演进,传统的单机自增ID已无法满足需求。高并发、高可用的分布式ID生成方案成为构建可靠分布式系统的必要条件。R...

基于OpenWrt系统路由器的模式切换与网页设计

摘要:目前商用WiFi路由器已应用到多个领域,商家通过给用户提供一个稳定免费WiFi热点达到吸引客户、提升服务的目标。传统路由器自带的Luci界面提供了工厂模式的Web界面,用户可通过该界面配置路...

这篇文章教你看明白 nginx-ingress 控制器

主机nginx一般nginx做主机反向代理(网关)有以下配置...

如何用redis实现注册中心

一句话总结使用Redis实现注册中心:服务注册...

爱可可老师24小时热门分享(2020.5.10)

No1.看自己以前写的代码是种什么体验?No2.DooM-chip!国外网友SylvainLefebvre自制的无CPU、无操作码、无指令计数器...No3.我认为CS学位可以更好,如...

Apportable:拯救程序员,IOS一秒变安卓

摘要:还在为了跨平台使用cocos2d-x吗,拯救objc程序员的奇葩来了,ApportableSDK:FreeAndroidsupportforcocos2d-iPhone。App...

JAVA实现超买超卖方案汇总,那个最适合你,一篇文章彻底讲透

以下是几种Java实现超买超卖问题的核心解决方案及代码示例,针对高并发场景下的库存扣减问题:方案一:Redis原子操作+Lua脚本(推荐)//使用Redis+Lua保证原子性publicbo...

3月26日更新 快速施法自动施法可独立设置

2016年3月26日DOTA2有一个79.6MB的更新主要是针对自动施法和快速施法的调整本来内容不多不少朋友都有自动施法和快速施法的困扰英文更新日志一些视觉BUG修复就不翻译了主要翻译自动施...

Redis 是如何提供服务的

在刚刚接触Redis的时候,最想要知道的是一个’setnameJhon’命令到达Redis服务器的时候,它是如何返回’OK’的?里面命令处理的流程如何,具体细节怎么样?你一定有问过自己...

lua _G、_VERSION使用

到这里我们已经把lua基础库中的函数介绍完了,除了函数外基础库中还有两个常量,一个是_G,另一个是_VERSION。_G是基础库本身,指向自己,这个变量很有意思,可以无限引用自己,最后得到的还是自己,...

China&#39;s top diplomat to chair third China-Pacific Island countries foreign ministers&#39; meeting

BEIJING,May21(Xinhua)--ChineseForeignMinisterWangYi,alsoamemberofthePoliticalBureau...

移动工作交流工具Lua推出Insights数据分析产品

Lua是一个适用于各种职业人士的移动交流平台,它在今天推出了一项叫做Insights的全新功能。Insights是一个数据平台,客户可以在上面实时看到员工之间的交流情况,并分析这些情况对公司发展的影响...

Redis 7新武器:用Redis Stack实现向量搜索的极限压测

当传统关系型数据库还在为向量相似度搜索的性能挣扎时,Redis7的RedisStack...

Nginx/OpenResty详解,Nginx Lua编程,重定向与内部子请求

重定向与内部子请求Nginx的rewrite指令不仅可以在Nginx内部的server、location之间进行跳转,还可以进行外部链接的重定向。通过ngx_lua模块的Lua函数除了能实现Nginx...