1. 程式人生 > 程式設計 >SpringBoot應用啟動流程原始碼解析

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,analyzers,ex);
   throw new IllegalStateException(ex);
  }
}

幾個重要的事件回撥機制

配置在META-INF/spring.factories

    ApplicationContextInitializer

    SpringApplicationRunListener

只需要放在ioc容器中

    ApplicationRunner

    CommandLineRunner

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。