zoukankan      html  css  js  c++  java
  • SpringBoot启动流程分析(二):SpringApplication的run方法

    SpringBoot系列文章简介

    SpringBoot源码阅读辅助篇:

      Spring IoC容器与应用上下文的设计与实现

    SpringBoot启动流程源码分析:

    1. SpringBoot启动流程分析(一):SpringApplication类初始化过程
    2. SpringBoot启动流程分析(二):SpringApplication的run方法
    3. SpringBoot启动流程分析(三):SpringApplication的run方法之prepareContext()方法
    4. SpringBoot启动流程分析(四):IoC容器的初始化过程
    5. SpringBoot启动流程分析(五):SpringBoot自动装配原理实现
    6. SpringBoot启动流程分析(六):IoC容器依赖注入

    笔者注释版Spring Framework与SpringBoot源码git传送门:请不要吝啬小星星

    1. spring-framework-5.0.8.RELEASE
    2. SpringBoot-2.0.4.RELEASE

    一、前言

      前一篇博客介绍了 SpringApplication 类的实例化过程,本章总结SpringBoot启动流程最重要的部分run方法。通过rrun方法梳理出SpringBoot启动的流程,然后后面的博客再一步步的分析启动流程中各个步骤所做的具体的工作。深入分析后会发现SpringBoot也就是给Spring包了一层皮,事先替我们准备好Spring所需要的环境及一些基础,具体通过源码一步步深入分析后会发现Spring是真的很伟大。当然跟代码的时候越深入越容易陷进去进而发现有些东西没法通过博客详细的梳理出来。当然在这个过程中还是立足于我们对SpringBoot的使用来说明源码所做的工作。知其然才能知其所以然。加油

    二、SpringBoot启动流程梳理

      首先摆上run方法的源码

     1 /**
     2  * Run the Spring application, creating and refreshing a new
     3  * {@link ApplicationContext}.
     4  *
     5  * @param args the application arguments (usually passed from a Java main method)
     6  * @return a running {@link ApplicationContext}
     7  *
     8  * 运行spring应用,并刷新一个新的 ApplicationContext(Spring的上下文)
     9  * ConfigurableApplicationContext 是 ApplicationContext 接口的子接口。在 ApplicationContext
    10  * 基础上增加了配置上下文的工具。 ConfigurableApplicationContext是容器的高级接口
    11  */
    12 public ConfigurableApplicationContext run(String... args) {
    13     //记录程序运行时间
    14     StopWatch stopWatch = new StopWatch();
    15     stopWatch.start();
    16     // ConfigurableApplicationContext Spring 的上下文
    17     ConfigurableApplicationContext context = null;
    18     Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
    19     configureHeadlessProperty();
    20     //从META-INF/spring.factories中获取监听器
    21     //1、获取并启动监听器
    22     SpringApplicationRunListeners listeners = getRunListeners(args);
    23     listeners.starting();
    24     try {
    25         ApplicationArguments applicationArguments = new DefaultApplicationArguments(
    26                 args);
    27         //2、构造应用上下文环境
    28         ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
    29         //处理需要忽略的Bean
    30         configureIgnoreBeanInfo(environment);
    31         //打印banner
    32         Banner printedBanner = printBanner(environment);
    33         ///3、初始化应用上下文
    34         context = createApplicationContext();
    35         //实例化SpringBootExceptionReporter.class,用来支持报告关于启动的错误
    36         exceptionReporters = getSpringFactoriesInstances(
    37                 SpringBootExceptionReporter.class,
    38                 new Class[]{ConfigurableApplicationContext.class}, context);
    39         //4、刷新应用上下文前的准备阶段
    40         prepareContext(context, environment, listeners, applicationArguments, printedBanner);
    41         //5、刷新应用上下文
    42         refreshContext(context);
    43         //刷新应用上下文后的扩展接口
    44         afterRefresh(context, applicationArguments);
    45         //时间记录停止
    46         stopWatch.stop();
    47         if (this.logStartupInfo) {
    48             new StartupInfoLogger(this.mainApplicationClass)
    49                     .logStarted(getApplicationLog(), stopWatch);
    50         }
    51         //发布容器启动完成事件
    52         listeners.started(context);
    53         callRunners(context, applicationArguments);
    54     } catch (Throwable ex) {
    55         handleRunFailure(context, ex, exceptionReporters, listeners);
    56         throw new IllegalStateException(ex);
    57     }
    58 
    59     try {
    60         listeners.running(context);
    61     } catch (Throwable ex) {
    62         handleRunFailure(context, ex, exceptionReporters, null);
    63         throw new IllegalStateException(ex);
    64     }
    65     return context;
    66 }

      具体的每一行代码的含义请看注释,我们在这先总结一下启动过程中的重要步骤:(笔者倾向于将应用上下文同容器区分开来)

    第一步:获取并启动监听器
    第二步:构造应用上下文环境
    第三步:初始化应用上下文
    第四步:刷新应用上下文前的准备阶段
    第五步:刷新应用上下文
    第六步:刷新应用上下文后的扩展接口

      OK,下面SpringBoot的启动流程分析,我们就根据这6大步骤进行详细解读。最总要的是第四,五步。我们会着重的分析。

    三、第一步:获取并启动监听器

      事件机制在Spring是很重要的一部分内容,通过事件机制我们可以监听Spring容器中正在发生的一些事件,同样也可以自定义监听事件。Spring的事件为Bean和Bean之间的消息传递提供支持。当一个对象处理完某种任务后,通知另外的对象进行某些处理,常用的场景有进行某些操作后发送通知,消息、邮件等情况。

    1 private SpringApplicationRunListeners getRunListeners(String[] args) {
    2     Class<?>[] types = new Class<?>[]{SpringApplication.class, String[].class};
    3     return new SpringApplicationRunListeners(logger, getSpringFactoriesInstances(
    4             SpringApplicationRunListener.class, types, this, args));
    5 }

      在这里面是不是看到一个熟悉的方法:getSpringFactoriesInstances(),可以看下下面的注释,前面的博文我们已经详细介绍过该方法是怎么一步步的获取到META-INF/spring.factories中的指定的key的value,获取到以后怎么实例化类的。

     1 /**
     2  * 通过指定的classloader 从META-INF/spring.factories获取指定的Spring的工厂实例
     3  * @param type
     4  * @param parameterTypes
     5  * @param args
     6  * @param <T>
     7  * @return
     8  */
     9 private <T> Collection<T> getSpringFactoriesInstances(Class<T> type,
    10                                                       Class<?>[] parameterTypes, Object... args) {
    11     ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    12     // Use names and ensure unique to protect against duplicates
    13     //通过指定的classLoader从 META-INF/spring.factories 的资源文件中,
    14     //读取 key 为 type.getName() 的 value
    15     Set<String> names = new LinkedHashSet<>(SpringFactoriesLoader.loadFactoryNames(type, classLoader));
    16     //创建Spring工厂实例
    17     List<T> instances = createSpringFactoriesInstances(type, parameterTypes,
    18             classLoader, args, names);
    19     //对Spring工厂实例排序(org.springframework.core.annotation.Order注解指定的顺序)
    20     AnnotationAwareOrderComparator.sort(instances);
    21     return instances;
    22 }

       回到run方法,debug这个代码 SpringApplicationRunListeners listeners = getRunListeners(args); 看一下获取的是哪个监听器:

      EventPublishingRunListener监听器是Spring容器的启动监听器。

       listeners.starting(); 开启了监听事件。

    四、第二步:构造应用上下文环境

      应用上下文环境包括什么呢?包括计算机的环境,Java环境,Spring的运行环境,Spring项目的配置(在SpringBoot中就是那个熟悉的application.properties/yml)等等。

      首先看一下prepareEnvironment()方法。

     1 private ConfigurableEnvironment prepareEnvironment(
     2         SpringApplicationRunListeners listeners,
     3         ApplicationArguments applicationArguments) {
     4     // Create and configure the environment
     5     //创建并配置相应的环境
     6     ConfigurableEnvironment environment = getOrCreateEnvironment();
     7     //根据用户配置,配置 environment系统环境
     8     configureEnvironment(environment, applicationArguments.getSourceArgs());
     9     // 启动相应的监听器,其中一个重要的监听器 ConfigFileApplicationListener 就是加载项目配置文件的监听器。
    10     listeners.environmentPrepared(environment);
    11     bindToSpringApplication(environment);
    12     if (this.webApplicationType == WebApplicationType.NONE) {
    13         environment = new EnvironmentConverter(getClassLoader())
    14                 .convertToStandardEnvironmentIfNecessary(environment);
    15     }
    16     ConfigurationPropertySources.attach(environment);
    17     return environment;
    18 }

       看上面的注释,方法中主要完成的工作,首先是创建并按照相应的应用类型配置相应的环境,然后根据用户的配置,配置系统环境,然后启动监听器,并加载系统配置文件。

    4.1、 ConfigurableEnvironment environment = getOrCreateEnvironment(); 

      看看getOrCreateEnvironment()干了些什么。

     1 private ConfigurableEnvironment getOrCreateEnvironment() {
     2     if (this.environment != null) {
     3         return this.environment;
     4     }
     5     //如果应用类型是 SERVLET 则实例化 StandardServletEnvironment
     6     if (this.webApplicationType == WebApplicationType.SERVLET) {
     7         return new StandardServletEnvironment();
     8     }
     9     return new StandardEnvironment();
    10 }

       通过代码可以看到根据不同的应用类型初始化不同的系统环境实例。前面咱们已经说过应用类型是怎么判断的了,这里就不在赘述了。

      

      从上面的继承关系可以看出,StandardServletEnvironment是StandardEnvironment的子类。这两个对象也没什么好讲的,当是web项目的时候,环境上会多一些关于web环境的配置。

    4.2、 configureEnvironment(environment, applicationArguments.getSourceArgs()); 

    1 protected void configureEnvironment(ConfigurableEnvironment environment,
    2                                     String[] args) {
    3     // 将main 函数的args封装成 SimpleCommandLinePropertySource 加入环境中。
    4     configurePropertySources(environment, args);
    5     // 激活相应的配置文件
    6     configureProfiles(environment, args);
    7 }

      在执行完方法中的两行代码后,debug的截图如下

      如下图所示,我在spring的启动参数中指定了参数:--spring.profiles.active=prod(关于这个参数的用法,点我,其实就是启动多个实例用的)

     

      在configurePropertySources(environment, args);中将args封装成了SimpleCommandLinePropertySource并加入到了environment中。

      configureProfiles(environment, args);根据启动参数激活了相应的配置文件。

      话不多说,debug一遍就明白了。

    4.3、 listeners.environmentPrepared(environment); 

      进入到方法一路跟下去就到了SimpleApplicationEventMulticaster类的multicastEvent()方法。

      

      查看getApplicationListeners(event, type)执行结果,发现一个重要的监听器ConfigFileApplicationListener。

      先看看这个类的注释

     1 /**
     2  * {@link EnvironmentPostProcessor} that configures the context environment by loading
     3  * properties from well known file locations. By default properties will be loaded from
     4  * 'application.properties' and/or 'application.yml' files in the following locations:
     5  * <ul>
     6  * <li>classpath:</li>
     7  * <li>file:./</li>
     8  * <li>classpath:config/</li>
     9  * <li>file:./config/:</li>
    10  * </ul>
    11  * <p>
    12  * Alternative search locations and names can be specified using
    13  * {@link #setSearchLocations(String)} and {@link #setSearchNames(String)}.
    14  * <p>
    15  * Additional files will also be loaded based on active profiles. For example if a 'web'
    16  * profile is active 'application-web.properties' and 'application-web.yml' will be
    17  * considered.
    18  * <p>
    19  * The 'spring.config.name' property can be used to specify an alternative name to load
    20  * and the 'spring.config.location' property can be used to specify alternative search
    21  * locations or specific files.
    22  * <p>
    23  * 从默认的位置加载配置文件,并将其加入 上下文的 environment变量中
    24  */

      这个监听器默认的从注释中<ul>标签所示的几个位置加载配置文件,并将其加入 上下文的 environment变量中。当然也可以通过配置指定。

      debug跳过 listeners.environmentPrepared(environment); 这一行,查看environment属性,果真如上面所说的,配置文件的配置信息已经添加上来了。

      

    五、第三步:初始化应用上下文

      在SpringBoot工程中,应用类型分为三种,如下代码所示。

     1 public enum WebApplicationType {
     2     /**
     3      * 应用程序不是web应用,也不应该用web服务器去启动
     4      */
     5     NONE,
     6     /**
     7      * 应用程序应作为基于servlet的web应用程序运行,并应启动嵌入式servlet web(tomcat)服务器。
     8      */
     9     SERVLET,
    10     /**
    11      * 应用程序应作为 reactive web应用程序运行,并应启动嵌入式 reactive web服务器。
    12      */
    13     REACTIVE
    14 }

      对应三种应用类型,SpringBoot项目有三种对应的应用上下文,我们以web工程为例,即其上下文为AnnotationConfigServletWebServerApplicationContext。

     1 public static final String DEFAULT_WEB_CONTEXT_CLASS = "org.springframework.boot."
     2         + "web.servlet.context.AnnotationConfigServletWebServerApplicationContext";
     3 public static final String DEFAULT_REACTIVE_WEB_CONTEXT_CLASS = "org.springframework."
     4         + "boot.web.reactive.context.AnnotationConfigReactiveWebServerApplicationContext";
     5 public static final String DEFAULT_CONTEXT_CLASS = "org.springframework.context."
     6         + "annotation.AnnotationConfigApplicationContext";
     7         
     8 protected ConfigurableApplicationContext createApplicationContext() {
     9     Class<?> contextClass = this.applicationContextClass;
    10     if (contextClass == null) {
    11         try {
    12             switch (this.webApplicationType) {
    13                 case SERVLET:
    14                     contextClass = Class.forName(DEFAULT_WEB_CONTEXT_CLASS);
    15                     break;
    16                 case REACTIVE:
    17                     contextClass = Class.forName(DEFAULT_REACTIVE_WEB_CONTEXT_CLASS);
    18                     break;
    19                 default:
    20                     contextClass = Class.forName(DEFAULT_CONTEXT_CLASS);
    21             }
    22         } catch (ClassNotFoundException ex) {
    23             throw new IllegalStateException(
    24                     "Unable create a default ApplicationContext, "
    25                             + "please specify an ApplicationContextClass",
    26                     ex);
    27         }
    28     }
    29     return (ConfigurableApplicationContext) BeanUtils.instantiateClass(contextClass);
    30 }

      我们先看一下AnnotationConfigServletWebServerApplicationContext的设计。

       关于他的继承体系,我们在前面的博客中<Spring IoC容器与应用上下文的设计与实现>已经详细介绍了,在此不再赘述。

      应用上下文可以理解成IoC容器的高级表现形式,应用上下文确实是在IoC容器的基础上丰富了一些高级功能。

      应用上下文对IoC容器是持有的关系。他的一个属性beanFactory就是IoC容器(DefaultListableBeanFactory)。所以他们之间是持有,和扩展的关系。

      接下来看GenericApplicationContext类

    1 public class GenericApplicationContext extends AbstractApplicationContext implements BeanDefinitionRegistry {
    2     private final DefaultListableBeanFactory beanFactory;
    3     ...
    4     public GenericApplicationContext() {
    5         this.beanFactory = new DefaultListableBeanFactory();
    6     }
    7     ...
    8 }

       beanFactory正是在AnnotationConfigServletWebServerApplicationContext实现的接口GenericApplicationContext中定义的。在上面createApplicationContext()方法中的, BeanUtils.instantiateClass(contextClass) 这个方法中,不但初始化了AnnotationConfigServletWebServerApplicationContext类,也就是我们的上下文context,同样也触发了GenericApplicationContext类的构造函数,从而IoC容器也创建了。仔细看他的构造函数,有没有发现一个很熟悉的类DefaultListableBeanFactory,没错,DefaultListableBeanFactory就是IoC容器真实面目了。在后面的refresh()方法分析中,DefaultListableBeanFactory是无处不在的存在感。

      debug跳过createApplicationContext()方法。

      如上图所示,context就是我们熟悉的上下文(也有人称之为容器,都可以,看个人爱好和理解),beanFactory就是我们所说的IoC容器的真实面孔了。细细感受下上下文和容器的联系和区别,对于我们理解源码有很大的帮助。在系列文章中,我们也是将上下文和容器严格区分开来的。

      

      原创不易,转载请注明出处。

      如有错误的地方还请留言指正。

    小小的码农,大大的梦想
  • 相关阅读:
    10-18 noip提高组模拟赛(codecomb)T2贪心
    vj1011:记忆化搜索
    vj1010:高精乘+细心模拟
    10-18 noip提高组模拟赛(codecomb)T1倍增[未填]
    CODEFORCES ROUND #273 DIV2
    Unkown2
    2014.first[未填]
    Unknown
    历年noip复赛试题整合
    快速幂(模板)
  • 原文地址:https://www.cnblogs.com/hello-shf/p/10992377.html
Copyright © 2011-2022 走看看