SpringBoot——启动配置原理

一、启动流程:

几个重要的事件回调机制

下面两个是配置在META-INF/spring.factories中的:

  • ApplicationContextInitializer
  • SpringApplicationRunListener

下面两个是配置在ioc容器中的

  • ApplicationRunner
  • CommandLineRunner

1、创建SpringApplication:

启动SpringBoot应用会先创建SpringApplication,再调用run方法。
在这里插入图片描述
new SpringApplication(主程序类)

  • 判断是否web应用
  • 加载并保存所有ApplicationContextInitializer(META-INF/spring.factories),
  • 加载并保存所有ApplicationListener
  • 获取到主程序类

创建SpringApplication其实就是调用了SpringApplication的构造函数,并在里面完成了应用类型的判断以及Initializers、Listeners等的加载。
在这里插入图片描述
(1)webApplicationType:返回当前web应用的类型
None:非web应用启动
SERVLET:基于servlet的web应用,并且使用嵌入式的server
REACTIVE:非阻塞
在这里插入图片描述

(2)初始化器和监听器加载
setInitializers:从META-INF/spring.factories下加载初始化器
setListeners:从META-INF/spring.factories下加载监听器
在这里插入图片描述
好多包中都有spring.factories,下面以autoconfiguration包举例:
在这里插入图片描述
启动之后,成功加载的初始化器和监听器
在这里插入图片描述
(3)deduceMainApplicationClass()
在这里插入图片描述

看传过来的类中,哪个类中有main方法,哪个类就是主程序。
在这里插入图片描述

2、run

run()

  • 回调所有的SpringApplicationRunListener(META-INF/spring.factories)的starting
  • 获取ApplicationArguments
  • 准备环境&回调所有监听器(SpringApplicationRunListener )的environmentPrepared
  • 打印banner信息
  • 创建ioc容器对象(web环境容器或者普通环境容器)
  • 准备环境
  • 执行ApplicationContextInitializer. initialize()
  • 监听器SpringApplicationRunListener回调contextPrepared
  • 加载主配置类定义信息
  • 监听器SpringApplicationRunListener回调contextLoaded
  • 刷新启动IOC容器;
  • 扫描加载所有容器中的组件(包括从META-INF/spring.factories中获取的所有EnableAutoConfiguration组件)
  • 回调容器中所有的ApplicationRunner、CommandLineRunner的run方法
  • 监听器SpringApplicationRunListener回调started方法和running方法

run方法的完整流程:
在这里插入图片描述
在这里插入图片描述

二、 事件监听机制测试

下面两个需要在META-INF/spring.factories中进行配置:

  • ApplicationContextInitializer
  • SpringApplicationRunListener

在这里插入图片描述

下面两个配置好后注入到ioc容器中即可

  • ApplicationRunner
  • CommandLineRunner
    在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/glpghz/article/details/111424694