SpringBoot应用启动流程源码解析

 更新时间:2020年04月16日 11:30:17   作者:TomDu  
这篇文章主要介绍了SpringBoot应用启动流程源码解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

前言

  Springboot应用在启动的时候分为两步:首先生成 SpringApplication 对象 ,运行 SpringApplication 的 run 方法,下面一一看一下每一步具体都干了什么

  public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {
    return new SpringApplication(primarySources).run(args);
  }

创建 SpringApplication 对象

public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
    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;然后保存起来
    setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
     //从类路径下找到ETA-INF/spring.factories配置的所有ApplicationListener 
    setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
     //从多个配置类中找到有main方法的主配置类 
    this.mainApplicationClass = deduceMainApplicationClass();
  }

其中从类路径下获取到META-INF/spring.factories配置的所有ApplicationContextInitializer和ApplicationListener的具体代码如下

public final class SpringFactoriesLoader {
  /**spring.factories的位置*/
  public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories";

  private static final Log logger = LogFactory.getLog(SpringFactoriesLoader.class);
  /**
  * 缓存扫描后的结果, 注意这个cache是static修饰的,说明是多个实例共享的
  * 其中MultiValueMap的key就是spring.factories中的key(比如org.springframework.boot.autoconfigure.EnableAutoConfiguration), 
  * 其值就是key对应的value以逗号分隔后得到的List集合(这里用到了MultiValueMap,他是guava的一键多值map, 类似Map<String, List<String>>)
  */
  private static final Map<ClassLoader, MultiValueMap<String, String>> cache = new ConcurrentReferenceHashMap<>();

  private SpringFactoriesLoader() {
  }
  
  /**
  * AutoConfigurationImportSelector及应用的初始化器和监听器里最终调用的就是这个方法,
  * 这里的factoryType是EnableAutoConfiguration.class、ApplicationContextInitializer.class、或ApplicationListener.class
  * classLoader是AutoConfigurationImportSelector、ApplicationContextInitializer、或ApplicationListener里的beanClassLoader
  */
  public static List<String> loadFactoryNames(Class<?> factoryType, @Nullable ClassLoader classLoader) {
    String factoryTypeName = factoryType.getName();
    return loadSpringFactories(classLoader).getOrDefault(factoryTypeName, Collections.emptyList());
  }
  
  /**
  * 加载 spring.factories文件的核心实现
  */
  private static Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader) {
    // 先从缓存获取,如果获取到了说明之前已经被加载过
    MultiValueMap<String, String> result = cache.get(classLoader);
    if (result != null) {
      return result;
    }

    try {
      // 找到所有jar中的spring.factories文件的地址
      Enumeration<URL> urls = (classLoader != null ?
          classLoader.getResources(FACTORIES_RESOURCE_LOCATION) :
          ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));
      result = new LinkedMultiValueMap<>();
      // 循环处理每一个spring.factories文件
      while (urls.hasMoreElements()) {
        URL url = urls.nextElement();
        UrlResource resource = new UrlResource(url);
        // 加载spring.factories文件中的内容到Properties对象中
        Properties properties = PropertiesLoaderUtils.loadProperties(resource);
        // 遍历spring.factories内容中的所有的键值对
        for (Map.Entry<?, ?> entry : properties.entrySet()) {
          // 获得spring.factories内容中的key(比如org.springframework.boot.autoconfigure.EnableAutoConfiguratio)
          String factoryTypeName = ((String) entry.getKey()).trim();
          // 获取value, 然后按英文逗号(,)分割得到value数组并遍历
          for (String factoryImplementationName : StringUtils.commaDelimitedListToStringArray((String) entry.getValue())) {
            // 存储结果到上面的多值Map中(MultiValueMap<String, String>)
            result.add(factoryTypeName, factoryImplementationName.trim());
          }
        }
      }
      cache.put(classLoader, result);
      return result;
    }
    catch (IOException ex) {
      throw new IllegalArgumentException("Unable to load factories from location [" +
          FACTORIES_RESOURCE_LOCATION + "]", ex);
    }
  }
}

运行run方法

public ConfigurableApplicationContext run(String... args) {
  //开始停止的监听
  StopWatch stopWatch = new StopWatch();
  stopWatch.start();
  //声明一个可配置的ioc容器
  ConfigurableApplicationContext context = null;
  FailureAnalyzers analyzers = null;
  //配置awt相关的东西
  configureHeadlessProperty();
  
  //获取SpringApplicationRunListeners;从类路径下META-INF/spring.factories
  SpringApplicationRunListeners listeners = getRunListeners(args);
  //回调所有的获取SpringApplicationRunListener.starting()方法
  listeners.starting();
  try {
    //封装命令行参数
   ApplicationArguments applicationArguments = new DefaultApplicationArguments(
      args);
   //准备环境
   ConfigurableEnvironment environment = prepareEnvironment(listeners,
      applicationArguments);
   //创建环境完成后回调SpringApplicationRunListener.environmentPrepared();表示环境准备完成
   Banner printedBanner = printBanner(environment);
    
    //创建ApplicationContext;决定创建web的ioc还是普通的ioc,
    //通过反射创建ioc容器((ConfigurableApplicationContext) BeanUtils.instantiateClass(contextClass);)
   context = createApplicationContext();
    //出现异常之后做异常分析报告
   analyzers = new FailureAnalyzers(context);
    //准备上下文环境;将environment保存到ioc中;而且applyInitializers();
    //applyInitializers():回调之前保存的所有的ApplicationContextInitializer的initialize方法
    //回调所有的SpringApplicationRunListener的contextPrepared();
    //
   prepareContext(context, environment, listeners, applicationArguments,
      printedBanner);
    //prepareContext运行完成以后回调所有的SpringApplicationRunListener的contextLoaded();
    
    //刷新容器;ioc容器初始化(如果是web应用还会创建嵌入式的Tomcat);Spring注解版
    //扫描,创建,加载所有组件的地方;(配置类,组件,自动配置)
   refreshContext(context);
    //从ioc容器中获取所有的ApplicationRunner和CommandLineRunner进行回调
    //ApplicationRunner先回调,CommandLineRunner再回调
   afterRefresh(context, applicationArguments);
    //所有的SpringApplicationRunListener回调finished方法
   listeners.finished(context, null);
   stopWatch.stop();
   if (this.logStartupInfo) {
     new StartupInfoLogger(this.mainApplicationClass)
        .logStarted(getApplicationLog(), stopWatch);
   }
    //整个SpringBoot应用启动完成以后返回启动的ioc容器;
   return context;
  }
  catch (Throwable ex) {
   handleRunFailure(context, listeners, analyzers, ex);
   throw new IllegalStateException(ex);
  }
}

几个重要的事件回调机制

配置在META-INF/spring.factories

    ApplicationContextInitializer

    SpringApplicationRunListener

只需要放在ioc容器中

    ApplicationRunner

    CommandLineRunner

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • Elasticsearch(ES)多种查询方式案例

    Elasticsearch(ES)多种查询方式案例

    Elasticsearch是一个分布式的RESTful搜索和分析引擎,可让您轻松地大规模存储,搜索和分析,这篇文章主要给大家介绍了关于Elasticsearch(ES)多种查询方式的相关资料,需要的朋友可以参考下
    2023-09-09
  • java向es中写入数据报错org.elasticsearch.action.ActionReque问题

    java向es中写入数据报错org.elasticsearch.action.ActionReque问题

    这篇文章主要介绍了java向es中写入数据报错org.elasticsearch.action.ActionReque问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-11-11
  • idea版本更新安装教程详解

    idea版本更新安装教程详解

    idea的更新版本比较特殊,需要重新安装一下,这篇文章给大家介绍idea版本更新安装教程详解,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧
    2020-11-11
  • 使用Java8进行分组(多个字段的组合分组)

    使用Java8进行分组(多个字段的组合分组)

    本文主要介绍了使用Java8进行分组(多个字段的组合分组),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-07-07
  • SpringBoot整合EasyExcel实现Excel表格导出功能

    SpringBoot整合EasyExcel实现Excel表格导出功能

    这篇文章主要介绍了SpringBoot整合EasyExcel实现Excel表格导出功能,文章围绕主题展开详细的内容介绍,具有一定的参考价值,需要的朋友可以参考一下
    2022-07-07
  • Spring与Mybatis相结合实现多数据源切换功能

    Spring与Mybatis相结合实现多数据源切换功能

    这篇文章主要介绍了Spring与Mybatis相结合实现多数据源切换功能的相关资料,非常不错,具有参考借鉴价值,需要的朋友可以参考下
    2016-06-06
  • sentinel配置 持久化到nacos的详细过程

    sentinel配置 持久化到nacos的详细过程

    这篇文章主要介绍了sentinel配置 持久化到nacos的详细过程,本文通过实例代码给大家介绍的非常详细,感兴趣的朋友一起看看吧
    2024-08-08
  • Java中二叉树的建立和各种遍历实例代码

    Java中二叉树的建立和各种遍历实例代码

    这篇文章主要介绍了Java中二叉树的建立和各种遍历实例代码,涉及树节点的定义,后序遍历,层序遍历,深度优先和广度优先等相关内容,具有一定借鉴价值,需要的朋友可以参考下
    2018-01-01
  • 解决java.lang.ClassCastException的java类型转换异常的问题

    解决java.lang.ClassCastException的java类型转换异常的问题

    这篇文章主要介绍了解决java.lang.ClassCastException的java类型转换异常的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-09-09
  • springMVC自定义注解,用AOP来实现日志记录的方法

    springMVC自定义注解,用AOP来实现日志记录的方法

    下面小编就为大家分享一篇springMVC自定义注解,用AOP来实现日志记录的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-01-01

最新评论