SpringBoot(二) 启动过程

2022-07-25,,

上一篇介绍了SpringBoot,本篇开始分析SpringBoot,从启动过程分析,中间穿插Spring一些重要的知识点,一起来看看SpringBoot的神奇与强大是如何实现的。

SpringBoot项目创建后,会自动生成一个启动类,这是一个包含main方法的启动类。

package cn.nec.test;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Repository;

@SpringBootApplication
public class CnNecTestApplication {

    public static void main(String[] args) {
        SpringApplication.run(CnNecTestApplication.class, args);
    }

}

如此简单的一个类,我们只需要执行main方法即可启动这个SpringBoot应用。
注解需要特定的解析器去解析使用,那么核心的看点就是SpringApplication.run(XXX.class, args)了。

进入这句代码可以看到,这块做了两件事:
创建SpringApplication对象
执行SpringApplication的run方法返回一个ConfigurableApplicationContext对象

创建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.lazyInitialization = false;
    this.resourceLoader = resourceLoader;
    Assert.notNull(primarySources, "PrimarySources must not be null");
    this.primarySources = new LinkedHashSet(Arrays.asList(primarySources));
    this.webApplicationType = WebApplicationType.deduceFromClasspath();
    this.setInitializers(this.getSpringFactoriesInstances(ApplicationContextInitializer.class));
    this.setListeners(this.getSpringFactoriesInstances(ApplicationListener.class));
    this.mainApplicationClass = this.deduceMainApplicationClass();
}

和上次看源码相比,又多了一些代码,不过核心代码没变,这也是Spring源码的特点,核心代码逻辑基本不会动。
上述代码分析:

  1. 设置Spring及SpringBoot启动过程中用到的一些参数的默认值
  2. 判断应用类型,类型有 非Web、响应式Web、Servlet,不同类型会创建不同的SpringContent
  3. setInitializers -> 获取项目路径下(META-INF/spring.factories)所有类型为ApplicationContextInitializer的Initializers.并通过反射创建实例.
  4. setListeners -> 获取项目路径下所有类型为ApplicationListener的Listeners. 并通过反射创建实例
  5. 查找并确定启动类class,这步暂时有点迷,目前看来主要用于日志打印。

这一步重要的点是:如何获取initializer和listener

解析SpringFactories并缓存

这一步其实非常重要,看字面意思,获取Spring的工厂类实例。通过解析项目路径下META-INF/spring.factories配置文件,获取所有类型的Spring工厂类名并根据类型缓存起来,需要获取特性类型的工厂类时,从缓存中直接取出来

获取特性类型的工厂类实例,通过反射创建工厂类

启动SpringApplication

/**
 * Run the Spring application, creating and refreshing a new
 * {@link ApplicationContext}.
 * @param args the application arguments (usually passed from a Java main method)
 * @return a running {@link ApplicationContext}
 */
public ConfigurableApplicationContext run(String... args) {
   StopWatch stopWatch = new StopWatch();
   stopWatch.start();
   ConfigurableApplicationContext context = null;
   Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
   configureHeadlessProperty();
   SpringApplicationRunListeners listeners = getRunListeners(args);
   listeners.starting();
   try {
      ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
      ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
      configureIgnoreBeanInfo(environment);
      Banner printedBanner = printBanner(environment);
      context = createApplicationContext();
      exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,
            new Class[] { ConfigurableApplicationContext.class }, context);
      prepareContext(context, environment, listeners, applicationArguments, printedBanner);
      refreshContext(context);
      afterRefresh(context, applicationArguments);
      stopWatch.stop();
      if (this.logStartupInfo) {
         new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
      }
      listeners.started(context);
      callRunners(context, applicationArguments);
   }
   catch (Throwable ex) {
      handleRunFailure(context, ex, exceptionReporters, listeners);
      throw new IllegalStateException(ex);
   }

   try {
      listeners.running(context);
   }
   catch (Throwable ex) {
      handleRunFailure(context, ex, exceptionReporters, null);
      throw new IllegalStateException(ex);
   }
   return context;
}
  1. 启动一个计时器并设置headless
  2. 获取项目路径下所有类型为SpringApplicationRunListener的Listeners.生成SpringApplicationRunListeners
    0 = “org.springframework.boot.context.event.EventPublishingRunListener”
  3. 使用观察者模式启动所有监听器(执行各个监听器的onApplicationEvent方法,做一些初始化操作)
  4. 设置环境变量environment
  5. 打印banner
  6. 创建applicationContext,根据第一步中的webApplicationType进行上下文对象初始化,一共三个
  7. 获取项目路径下所有类型为SpringBootExceptionReporter的Reporter并创建实例
  8. 上下文前置处理prepareContext,此步尤为重要,刷新上下文前的准备工作
  9. 刷新上下文,初始化容器
  10. 上下文后置处理afterRefresh,收尾工作
  11. 上下文准备完成,停止计时,打印应用启动完成
  12. 上下文发布一个应用已启动的事件给所有监听着,此处待确认到底想干啥
  13. 启动所有的runner,callRunners,类型为ApplicationRunner和CommandLineRunner的所有runner,此步待确认是否为启动定时器
  14. 上下文发布一个应用已准备好的事件给所有监听着,此处待确认到底想干啥
  15. 返回上下文,至此应用启动完成

本文地址:https://blog.csdn.net/u012098021/article/details/111917421

《SpringBoot(二) 启动过程.doc》

下载本文的Word格式文档,以方便收藏与打印。