1. 程式人生 > >Spring boot啟動流程原始碼解析

Spring boot啟動流程原始碼解析

閱讀須知

  • 版本:2.0.4
  • 文章中使用/* */註釋的方法會做深入分析

正文

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

這段程式碼相信大家都很熟悉,spring boot的啟動類,我們就以這段程式碼作為切入點,來分析spring boot的啟動流程:
SpringApplication:

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

public static ConfigurableApplicationContext run(Class<?>[] primarySources,
        String[] args) {
    /* 構建SpringApplication並執行,建立並且重新整理一個新的ApplicationContext */
return new SpringApplication(primarySources).run(args); }

SpringApplication:

public SpringApplication(Class<?>... primarySources) {
    this(null, primarySources);
}

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 = deduceWebApplicationType(); /* 獲取並設定Spring上下文初始化器 */ setInitializers((Collection) getSpringFactoriesInstances( ApplicationContextInitializer.class)); /* 獲取並設定Spring應用監聽器 */ setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class)); // 追述到應用主類,也就是main方法所在的類 this.mainApplicationClass = deduceMainApplicationClass(); }

這裡ApplicationContextInitializer和ApplicationListener我們會在後面用到的時候說明它們的作用。
SpringApplication:

private <T> Collection<T> getSpringFactoriesInstances(Class<T> type) {
    return getSpringFactoriesInstances(type, new Class<?>[] {});
}

private <T> Collection<T> getSpringFactoriesInstances(Class<T> type,
        Class<?>[] parameterTypes, Object... args) {
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    /* 載入工廠名稱,Set防止重複 */
    Set<String> names = new LinkedHashSet<>(
            SpringFactoriesLoader.loadFactoryNames(type, classLoader));
    // 建立工廠例項
    List<T> instances = createSpringFactoriesInstances(type, parameterTypes,
            classLoader, args, names);
    // 根據@Order和@Priority進行排序
    AnnotationAwareOrderComparator.sort(instances);
    return instances;
}

SpringFactoriesLoader:

public static List<String> loadFactoryNames(Class<?> factoryClass, @Nullable ClassLoader classLoader) {
    String factoryClassName = factoryClass.getName();
    /* 載入工廠配置,根據傳入的factoryClass獲取工廠名稱集合 */
    return loadSpringFactories(classLoader).getOrDefault(factoryClassName, Collections.emptyList());
}

SpringFactoriesLoader:

private static Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader) {
    MultiValueMap<String, String> result = cache.get(classLoader);
    if (result != null) {
        return result;
    }
    try {
        // 載入資源,路徑META-INF/spring.factories
        Enumeration<URL> urls = (classLoader != null ?
                classLoader.getResources(FACTORIES_RESOURCE_LOCATION) :
                ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));
        result = new LinkedMultiValueMap<>();
        while (urls.hasMoreElements()) {
            URL url = urls.nextElement();
            UrlResource resource = new UrlResource(url);
            Properties properties = PropertiesLoaderUtils.loadProperties(resource);
            for (Map.Entry<?, ?> entry : properties.entrySet()) {
                // value用逗號分隔組成集合
                List<String> factoryClassNames = Arrays.asList(
                        StringUtils.commaDelimitedListToStringArray((String) entry.getValue()));
                // 新增key和集合的對映
                result.addAll((String) entry.getKey(), factoryClassNames);
            }
        }
        // 結果快取
        cache.put(classLoader, result);
        return result;
    }
    catch (IOException ex) {
        throw new IllegalArgumentException("Unable to load factories from location [" +
                FACTORIES_RESOURCE_LOCATION + "]", ex);
    }
}

我們來看一下META-INF/spring.factories檔案中有什麼內容:

# PropertySource Loaders
org.springframework.boot.env.PropertySourceLoader=\
org.springframework.boot.env.PropertiesPropertySourceLoader,\
org.springframework.boot.env.YamlPropertySourceLoader

# Run Listeners
org.springframework.boot.SpringApplicationRunListener=\
org.springframework.boot.context.event.EventPublishingRunListener

# Error Reporters
org.springframework.boot.SpringBootExceptionReporter=\
org.springframework.boot.diagnostics.FailureAnalyzers

# Application Context Initializers
org.springframework.context.ApplicationContextInitializer=\
org.springframework.boot.context.ConfigurationWarningsApplicationContextInitializer,\
org.springframework.boot.context.ContextIdApplicationContextInitializer,\
org.springframework.boot.context.config.DelegatingApplicationContextInitializer,\
org.springframework.boot.web.context.ServerPortInfoApplicationContextInitializer

# Application Listeners
org.springframework.context.ApplicationListener=\
org.springframework.boot.ClearCachesApplicationListener,\
org.springframework.boot.builder.ParentContextCloserApplicationListener,\
org.springframework.boot.context.FileEncodingApplicationListener,\
org.springframework.boot.context.config.AnsiOutputApplicationListener,\
org.springframework.boot.context.config.ConfigFileApplicationListener,\
org.springframework.boot.context.config.DelegatingApplicationListener,\
org.springframework.boot.context.logging.ClasspathLoggingApplicationListener,\
org.springframework.boot.context.logging.LoggingApplicationListener,\
org.springframework.boot.liquibase.LiquibaseServiceLocatorApplicationListener

# Environment Post Processors
org.springframework.boot.env.EnvironmentPostProcessor=\
org.springframework.boot.cloud.CloudFoundryVcapEnvironmentPostProcessor,\
org.springframework.boot.env.SpringApplicationJsonEnvironmentPostProcessor,\
org.springframework.boot.env.SystemEnvironmentPropertySourceEnvironmentPostProcessor

# Failure Analyzers
org.springframework.boot.diagnostics.FailureAnalyzer=\
org.springframework.boot.diagnostics.analyzer.BeanCurrentlyInCreationFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.BeanNotOfRequiredTypeFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.BindFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.BindValidationFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.UnboundConfigurationPropertyFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.ConnectorStartFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.NoUniqueBeanDefinitionFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.PortInUseFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.ValidationExceptionFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.InvalidConfigurationPropertyNameFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.InvalidConfigurationPropertyValueFailureAnalyzer

# FailureAnalysisReporters
org.springframework.boot.diagnostics.FailureAnalysisReporter=\
org.springframework.boot.diagnostics.LoggingFailureAnalysisReporter

檔案中我們看到了ApplicationContextInitializer和ApplicationListener的key value配置,還有一些其他的介面,遇到後我們在進行分析。構建好SpringApplication後,接下來就是執行它的run方法:
SpringApplication:

public ConfigurableApplicationContext run(String... args) {
    // StopWatch是一個簡單的秒錶,允許多個任務的計時,暴露每個命名任務的總執行時間和執行時間
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    ConfigurableApplicationContext context = null;
    Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
    configureHeadlessProperty();
    // 獲取SpringApplicationRunListener集合,同樣是從上面載入的配置中獲取
    SpringApplicationRunListeners listeners = getRunListeners(args);
    listeners.starting();
    try {
        ApplicationArguments applicationArguments = new DefaultApplicationArguments(
                args);
        /* 準備環境 */
        ConfigurableEnvironment environment = prepareEnvironment(listeners,
                applicationArguments);
        configureIgnoreBeanInfo(environment);
        // 列印banner,就是我們在控制檯看到的那個Spring的logo
        Banner printedBanner = printBanner(environment);
        // 根據不同的webApplicationType返回不同的應用上下文例項
        context = createApplicationContext();
        // 同樣從上面載入的配置中獲取SpringBootExceptionReporter
        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);
        // 呼叫所有ApplicationRunner和CommandLineRunner的run方法
        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;
}

在這裡我們看到很多處SpringApplicationRunListener的相關方法呼叫,我們來說明一下它的作用,就像它的命名一樣,主要是監聽SpringApplication的run方法的各個關鍵步驟,在上面載入的配置中,我們看到了一個實現為EventPublishingRunListener,主要作用是釋出應用的啟動執行、啟動完成等一些關鍵事件,具體程式碼有興趣的同學可以自行查閱。
SpringApplication:

private ConfigurableEnvironment prepareEnvironment(
        SpringApplicationRunListeners listeners,
        ApplicationArguments applicationArguments) {
    // 建立Environment
    ConfigurableEnvironment environment = getOrCreateEnvironment();
    /* 配置environment */
    configureEnvironment(environment, applicationArguments.getSourceArgs());
    listeners.environmentPrepared(environment);
    // 將environment繫結到SpringApplication
    bindToSpringApplication(environment);
    if (this.webApplicationType == WebApplicationType.NONE) {
        environment = new EnvironmentConverter(getClassLoader())
                .convertToStandardEnvironmentIfNecessary(environment);
    }
    // 附加一個ConfigurationPropertySource到environment
    ConfigurationPropertySources.attach(environment);
    return environment;
}

SpringApplication:

protected void configureEnvironment(ConfigurableEnvironment environment,
        String[] args) {
    // 在此應用程式的環境中新增、刪除或重新排序PropertySource
    configurePropertySources(environment, args);
    // 配置此應用程式環境的啟用(或預設為啟用)配置檔案
    // 可以通過spring.profiles.active屬性在配置檔案處理期間啟用其他配置檔案
    configureProfiles(environment, args);
}

SpringApplication:

private void prepareContext(ConfigurableApplicationContext context,
        ConfigurableEnvironment environment, SpringApplicationRunListeners listeners,
        ApplicationArguments applicationArguments, Banner printedBanner) {
    context.setEnvironment(environment);
    // 應用相應的ApplicationContext後置處理,子類可以覆蓋,
    // 預設實現為context設定beanNameGenerator和resourceLoader
    postProcessApplicationContext(context);
    // 在context重新整理之前應用之前載入的ApplicationContextInitializer
    // 在META-INF/spring.factories中預設配置了4個ApplicationContextInitializer,具體作用可以自行了解一下
    applyInitializers(context);
    listeners.contextPrepared(context);
    // 日誌列印
    if (this.logStartupInfo) {
        logStartupInfo(context.getParent() == null);
        logStartupProfileInfo(context);
    }
    // 新增特定的boot單例bean
    context.getBeanFactory().registerSingleton("springApplicationArguments",
            applicationArguments);
    if (printedBanner != null) {
        context.getBeanFactory().registerSingleton("springBootBanner", printedBanner);
    }
    // 獲取所有資源,示例中就是獲取到我們的啟動類
    Set<Object> sources = getAllSources();
    Assert.notEmpty(sources, "Sources must not be empty");
    // 載入資源註冊成為Spring的bean
    load(context, sources.toArray(new Object[0]));
    listeners.contextLoaded(context);
}

SpringApplication:

private void refreshContext(ConfigurableApplicationContext context) {
    refresh(context);
    if (this.registerShutdownHook) {
        try {
            context.registerShutdownHook();
        }
        catch (AccessControlException ex) {
        }
    }
}

這裡上下文的重新整理和註冊關閉鉤子我們都在之前的Spring原始碼分析文章中分析過,不再贅述。讀者可能會有疑惑,Spring boot不是有非常厲害的自動配置麼,文章中並沒有看到啊,Spring boot的自動配置我們會用單獨的文章來分析,本篇文章我們主要分析整個啟動流程的步驟和一些擴充套件,到這裡,整個Spring boot的啟動流程就分析完了。