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

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

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

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

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

相关推荐

十年之重修Redis原理(redis重试机制)

弱小和无知并不是生存的障碍,傲慢才是。--------面试者...

Redis 中ZSET数据类型命令使用及对应场景总结

1.zadd添加元素zaddkeyscoremember...

redis总结(redis常用)

RedisTemplate封装的工具类packagehk.com.easyview.common.helper;importcom.alibaba.fastjson.JSONObject;...

配置热更新系统(如何实现热更新)

整体设计概览┌────────────┐┌────────────────┐┌────────────┐│配置后台服务│--写入-->│Red...

java高级用法之:调用本地方法的利器JNA

简介JAVA是可以调用本地方法的,官方提供的调用方式叫做JNI,全称叫做javanativeinterface。要想使用JNI,我们需要在JAVA代码中定义native方法,然后通过javah命令...

SpringBoot:如何优雅地进行响应数据封装、异常处理

背景越来越多的项目开始基于前后端分离的模式进行开发,这对后端接口的报文格式便有了一定的要求。通常,我们会采用JSON格式作为前后端交换数据格式,从而减少沟通成本等。...

Java中有了基本类型为什么还要有包装类型(封装类型)

Java中基本数据类型与包装类型有:...

java面向对象三大特性:封装、继承、多态——举例说明(转载)

概念封装:封装就是将客观的事物抽象成类,类中存在属于这个类的属性和方法。...

java 面向对象编程:封装、继承、多态

Java中的封装(Encapsulation)、继承(Inheritance)和多态(Polymorphism)是面向对象编程的三大基本概念。它们有助于提高代码的可重用性、可扩展性和可维护性。...

怎样解析java中的封装(怎样解析java中的封装文件)

1.解析java中的封装1.1以生活中的例子为例,打开电视机的时候你只需要按下开关键,电视机就会打开,我们通过这个操作我们可以去间接的对电视机里面的元器件进行亮屏和显示界面操作,具体怎么实现我们并不...

python 示例代码(python代码详解)

以下是35个python代码示例,涵盖了从基础到高级的各种应用场景。这些示例旨在帮助你学习和理解python编程的各个方面。1.Hello,World!#python...

python 进阶突破——内置模块(Standard Library)

Python提供了丰富的内置模块(StandardLibrary),无需安装即可直接使用。以下是一些常用的内置模块及其主要功能:1.文件与系统操作...

Python程序员如何调试和分析Python脚本程序?附代码实现

调试和分析Python脚本程序调试技术和分析技术在Python开发中发挥着重要作用。调试器可以设置条件断点,帮助程序员分析所有代码。而分析器可以运行程序,并提供运行时的详细信息,同时也能找出程序中的性...

python中,函数和方法异同点(python方法和函数的区别)

在Python中,函数(Function)...

Python入门基础命令详解(python基础入门教程)

以下是Python基本命令的详解指南,专为初学者设计,涵盖基础语法、常用操作和实用示例:Python基本命令详解:入门必备指南1.Python简介特点:简洁易读、跨平台、丰富的库支持...