Springboot 2启动源码流程

以使用静态方法SpringApplication.run(Bootstrap.class, args)启动 Springboot 为例,启动流程主要分为 SpringApplication 的创建和运行两部分;

创建

  1. 设置资源加载器,此处为空
  2. 设置 Springboot 启动类
  3. 根据类路径判断 web 类型,默认为 SERVLET->Spring MVC
  4. 读取每个 jar 包的 /META-INF/spring.factories 文件,获取 key 为 org.springframework.context.ApplicationContextInitializer 的值,即初始化器
  5. 读取每个 jar 包的 /META-INF/spring.factories 文件,获取 key 为 org.springframework.context.ApplicationListener 的值,即监听器
  6. 从当前的运行时堆栈元素中,找到 main 方法所在类

运行

  1. 启动计时秒表
  2. 读取每个 jar 包的 /META-INF/spring.factories 文件,获取 key 为 org.springframework.boot.SpringApplicationRunListener 的值,即 Springboot 的运行监听器,默认有 EventPublishingRunListener
  3. 启动监听器,使用事件派发器向监听器派发 ApplicationStartingEvent 事件
  4. 根据命令行参数 args 初始化 DefaultApplicationArguments
  5. 获取环境配置,绑定到 Spring 应用,并派发 ApplicationEnvironmentPreparedEvent 事件
  6. 配置 spring.beaninfo.ignore 指定的可以忽略的 Bean
  7. 打印 Banner
  8. 根据 web 类型创建上下文,默认为 AnnotationConfigServletWebServerApplicationContext
  9. 读取每个 jar 包的 /META-INF/spring.factories 文件,获取 key 为 org.springframework.boot.SpringBootExceptionReporter 的值,即失败分析器,默认有 FailureAnalyzers
  10. 准备上下文,即给它配置属性,回调初始化器,并派发 ApplicationPreparedEvent 事件
  11. 刷新容器,创建 Bean 的过程,调用 refresh() 方法,见 Spring 源码总结
  12. 刷新后的处理,空方法,子类可以实现该方法做额外的处理
  13. 停止秒表,打印启动时长
  14. 派发 ApplicationStartedEvent 事件
  15. 调用 ApplicationRunner、CommandLineRunner 的实现方法
  16. 派发 ApplicationReadyEvent 事件
  17. 如果启动过程发生异常,派发 ApplicationFailedEvent 事件,并执行失败分析器

一些初始化器和监听器的作用

初始化器

  1. DelegatingApplicationContextInitializer:获取环境配置 context.initializer.classes 指定的初始化器。
  2. ContextIdApplicationContextInitializer:初始化 Spring 应用名 ID:profile:PORT。(spring.application.name:spring.profiles.active:spring.application.name)
  3. ConfigurationWarningsApplicationContextInitializer:初始化配置检查,输出警告日志。
  4. ServerPortInfoApplicationContextInitializer:初始化对 WebServerInitializedEvent 事件的监听,将监听器添加到派发器
  5. SharedMetadataReaderFactoryContextInitializer:初始化元数据读取和缓存的后置处理器 CachingMetadataReaderFactoryPostProcessor。

监听器

  1. ConfigFileApplicationListener:加载默认路径下的配置文件。
  2. AnsiOutputApplicationListener:监听 spring.output.ansi.enabled 是否配置了彩色输出日志。always:启用彩色输出;ever禁用彩色输出;detect:(默认)自动检测。
  3. LoggingApplicationListener:配置日志系统。
  4. ClasspathLoggingApplicationListener:打印程序开始启动和启动失败 classpath 的 debug 日志。
  5. BackgroundPreinitializer:起一个后台线程触发早期的初始化器,包括校验器、消息转换器等。(MessageConverterInitializer、MBeanFactoryInitializer、ValidationInitializer、JacksonInitializer、ConversionServiceInitializer)
  6. DelegatingApplicationListener:获取环境配置 context.listener.classes 指定的监听器
  7. ParentContextCloserApplicationListener:如果父关闭了,则关闭应用程序上下文。它监听 refresh 事件来获取上下文,监听到关闭事件后进行传播。
  8. FileEncodingApplicationListener:如果系统文件和环境中配置的编码不匹配,则停止应用程序。
  9. ClearCachesApplicationListener:上下文加载后清理缓存。
posted @ 2019-08-15 01:26  O'Neal  阅读(604)  评论(0编辑  收藏  举报