Spring Boot 2.x 啟動全過程源碼分析

原創(chuàng): 不羈碼農(nóng) Java技術(shù)棧
原文地址: https://mp.weixin.qq.com/s?__biz=MzI3ODcxMzQzMw==&mid=2247486661&idx=1&sn=ef3308c7a392cb01e3788fd183ee0eff&chksm=eb5389f3dc2400e5a258b338dca36f7d20b46393daa494234ba1b706787413b861cdbc73197f&scene=21#wechat_redirect

Spring Boot 的應(yīng)用教程我們已經(jīng)分享過很多了,今天來通過源碼來分析下它的啟動過程,探究下 Spring Boot 為什么這么簡便的奧秘。

本篇基于 Spring Boot 2.0.3 版本進行分析,閱讀本文需要有一些 Java 和 Spring 框架基礎(chǔ),如果還不知道 Spring Boot 是什么,建議先看下我們的 Spring Boot 教程。

Spring Boot 的入口類

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

做過 Spring Boot 項目的都知道,上面是 Spring Boot 最簡單通用的入口類。入口類的要求是最頂層包下面第一個含有 main 方法的類,使用注解 @SpringBootApplication 來啟用 Spring Boot 特性,使用 SpringApplication.run 方法來啟動 Spring Boot 項目。

來看一下這個類的run方法調(diào)用關(guān)系源碼:

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

第一個參數(shù)primarySource:加載的主要資源類

第二個參數(shù) args:傳遞給應(yīng)用的應(yīng)用參數(shù)

先用主要資源類來實例化一個 SpringApplication 對象,再調(diào)用這個對象的 run 方法,所以我們分兩步來分析這個啟動源碼。

SpringApplication 的實例化過程

接著上面的 SpringApplication 構(gòu)造方法進入以下源碼:

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

public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
    // 1、資源初始化資源加載器為 null
    this.resourceLoader = resourceLoader;

    // 2、斷言主要加載資源類不能為 null,否則報錯
    Assert.notNull(primarySources, "PrimarySources must not be null");

    // 3、初始化主要加載資源類集合并去重
    this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));

    // 4、推斷當(dāng)前 WEB 應(yīng)用類型
    this.webApplicationType = deduceWebApplicationType();

    // 5、設(shè)置應(yīng)用上線文初始化器
    setInitializers((Collection) getSpringFactoriesInstances(
            ApplicationContextInitializer.class));      

    // 6、設(shè)置監(jiān)聽器
    setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));

    // 7、推斷主入口應(yīng)用類
    this.mainApplicationClass = deduceMainApplicationClass();

}

可知這個構(gòu)造器類的初始化包括以下 7 個過程。
1. 資源初始化資源加載器為 null

this.resourceLoader = resourceLoader;

2. 斷言主要加載資源類不能為 null,否則報錯

Assert.notNull(primarySources, "PrimarySources must not be null");

3. 初始化主要加載資源類集合并去重

this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));

4. 推斷當(dāng)前 WEB 應(yīng)用類型

this.webApplicationType = deduceWebApplicationType();

來看下 deduceWebApplicationType 方法和相關(guān)的源碼:

private WebApplicationType deduceWebApplicationType() {
    if (ClassUtils.isPresent(REACTIVE_WEB_ENVIRONMENT_CLASS, null)
            && !ClassUtils.isPresent(MVC_WEB_ENVIRONMENT_CLASS, null)) {
        return WebApplicationType.REACTIVE;
    }
    for (String className : WEB_ENVIRONMENT_CLASSES) {
        if (!ClassUtils.isPresent(className, null)) {
            return WebApplicationType.NONE;
        }
    }
    return WebApplicationType.SERVLET;
}

private static final String REACTIVE_WEB_ENVIRONMENT_CLASS = "org.springframework."
        + "web.reactive.DispatcherHandler";

private static final String MVC_WEB_ENVIRONMENT_CLASS = "org.springframework."
        + "web.servlet.DispatcherServlet";

private static final String[] WEB_ENVIRONMENT_CLASSES = { "javax.servlet.Servlet",
            "org.springframework.web.context.ConfigurableWebApplicationContext"
 };      

public enum WebApplicationType {

    /**
     * 非 WEB 項目
     */
    NONE,

    /**
     * SERVLET WEB 項目
     */
    SERVLET,

    /**
    * 響應(yīng)式 WEB 項目
     */
     REACTIVE

}

這個就是根據(jù)類路徑下是否有對應(yīng)項目類型的類推斷出不同的應(yīng)用類型。

5. 設(shè)置應(yīng)用上線文初始化器

setInitializers((Collection) getSpringFactoriesInstances(
            ApplicationContextInitializer.class));

ApplicationContextInitializer 的作用是什么?源碼如下。

public interface ApplicationContextInitializer<C extends ConfigurableApplicationContext> {

    /**
     * Initialize the given application context.
     * @param applicationContext the application to configure
     */
    void initialize(C applicationContext);

}

用來初始化指定的 Spring 應(yīng)用上下文,如注冊屬性資源、激活 Profiles 等。

來看下 setInitializers 方法源碼,其實就是初始化一個 ApplicationContextInitializer 應(yīng)用上下文初始化器實例的集合。

public void setInitializers(
        Collection<? extends ApplicationContextInitializer<?>> initializers) {
    this.initializers = new ArrayList<>();
    this.initializers.addAll(initializers);
}

再來看下這個初始化 getSpringFactoriesInstances 方法和相關(guān)的源碼:

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();
    // Use names and ensure unique to protect against duplicates
    Set<String> names = new LinkedHashSet<>(
            SpringFactoriesLoader.loadFactoryNames(type, classLoader));
    List<T> instances = createSpringFactoriesInstances(type, parameterTypes,
            classLoader, args, names);
    AnnotationAwareOrderComparator.sort(instances);
    return instances;
}

設(shè)置應(yīng)用上下文初始化器可分為以下 5 個步驟。

  • 5.1 獲取當(dāng)前線程上下文類加載器
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
  • 5.2 獲取 `ApplicationContextInitializer 的實例名稱集合并去重
Set<String> names = new LinkedHashSet<>(
                SpringFactoriesLoader.loadFactoryNames(type, classLoader));

loadFactoryNames 方法相關(guān)的源碼如下:

public static List<String> loadFactoryNames(Class<?> factoryClass, @Nullable ClassLoader classLoader) {
    String factoryClassName = factoryClass.getName();
    return loadSpringFactories(classLoader).getOrDefault(factoryClassName, Collections.emptyList());
}

public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/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 {
        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()) {
                List<String> factoryClassNames = Arrays.asList(
                        StringUtils.commaDelimitedListToStringArray((String) entry.getValue()));
                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);
    }
}

根據(jù)類路徑下的 META-INF/spring.factories 文件解析并獲取 ApplicationContextInitializer 接口的所有配置的類路徑名稱。

spring-boot-autoconfigure-2.0.3.RELEASE.jar!/META-INF/spring.factories 的初始化器相關(guān)配置內(nèi)容如下:

# Initializers
org.springframework.context.ApplicationContextInitializer=\
org.springframework.boot.autoconfigure.SharedMetadataReaderFactoryContextInitializer,\
org.springframework.boot.autoconfigure.logging.ConditionEvaluationReportLoggingListener
  • 5.3 根據(jù)以上類路徑創(chuàng)建初始化器實例列表
List<T> instances = createSpringFactoriesInstances(type, parameterTypes,
                classLoader, args, names);

private <T> List<T> createSpringFactoriesInstances(Class<T> type,
        Class<?>[] parameterTypes, ClassLoader classLoader, Object[] args,
        Set<String> names) {
    List<T> instances = new ArrayList<>(names.size());
    for (String name : names) {
        try {
            Class<?> instanceClass = ClassUtils.forName(name, classLoader);
            Assert.isAssignable(type, instanceClass);
            Constructor<?> constructor = instanceClass
                    .getDeclaredConstructor(parameterTypes);
            T instance = (T) BeanUtils.instantiateClass(constructor, args);
            instances.add(instance);
        }
        catch (Throwable ex) {
            throw new IllegalArgumentException(
                    "Cannot instantiate " + type + " : " + name, ex);
        }
    }
    return instances;
}
  • 5.4 初始化器實例列表排序
AnnotationAwareOrderComparator.sort(instances);
  • 5.5 返回初始化器實例列表
return instances;

6. 設(shè)置監(jiān)聽器

setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));

ApplicationListener 的作用是什么?源碼如下。

@FunctionalInterface
public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {

    /**
     * Handle an application event.
     * @param event the event to respond to
     */
    void onApplicationEvent(E event);

}

看源碼,這個接口繼承了 JDK 的 java.util.EventListener 接口,實現(xiàn)了觀察者模式,它一般用來定義感興趣的事件類型,事件類型限定于 ApplicationEvent的子類,這同樣繼承了 JDK 的 java.util.EventObject 接口。

設(shè)置監(jiān)聽器和設(shè)置初始化器調(diào)用的方法是一樣的,只是傳入的類型不一樣,設(shè)置監(jiān)聽器的接口類型為: getSpringFactoriesInstances,對應(yīng)的 spring-boot-autoconfigure-2.0.3.RELEASE.jar!/META-INF/spring.factories 文件配置內(nèi)容請見下方。

# Application Listeners
org.springframework.context.ApplicationListener=\
org.springframework.boot.autoconfigure.BackgroundPreinitializer

可以看出目前只有一個 BackgroundPreinitializer 監(jiān)聽器。
7.推斷主入口應(yīng)用類

this.mainApplicationClass = deduceMainApplicationClass();

private Class<?> deduceMainApplicationClass() {
    try {
        StackTraceElement[] stackTrace = new RuntimeException().getStackTrace();
        for (StackTraceElement stackTraceElement : stackTrace) {
            if ("main".equals(stackTraceElement.getMethodName())) {
                return Class.forName(stackTraceElement.getClassName());
            }
        }
    }
    catch (ClassNotFoundException ex) {
        // Swallow and continue
    }
    return null;
}

這個推斷入口應(yīng)用類的方式有點特別,通過構(gòu)造一個運行時異常,再遍歷異常棧中的方法名,獲取方法名為 main 的棧幀,從來得到入口類的名字再返回該類。

總結(jié)

源碼分析內(nèi)容有點多,也很麻煩,本章暫時分析到 SpringApplication 構(gòu)造方法的初始化流程,下章再繼續(xù)分析其 run 方法


第二篇

原創(chuàng): 不羈碼農(nóng) Java技術(shù)棧
原文地址:https://mp.weixin.qq.com/s?__biz=MzI3ODcxMzQzMw%3D%3D&mid=2247486739&idx=1&sn=174827f0ff5fb6c999e65ee80266bc39#wechat_redirect

SpringApplication 實例 run 方法運行過程


上面分析了 SpringApplication 實例對象構(gòu)造方法初始化過程,下面繼續(xù)來看下這個 SpringApplication 對象的 run 方法的源碼和運行流程。

public ConfigurableApplicationContext run(String... args) {
    // 1、創(chuàng)建并啟動計時監(jiān)控類
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();

    // 2、初始化應(yīng)用上下文和異常報告集合
    ConfigurableApplicationContext context = null;
    Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();

    // 3、設(shè)置系統(tǒng)屬性 `java.awt.headless` 的值,默認(rèn)值為:true
    configureHeadlessProperty();

    // 4、創(chuàng)建所有 Spring 運行監(jiān)聽器并發(fā)布應(yīng)用啟動事件
    SpringApplicationRunListeners listeners = getRunListeners(args);
    listeners.starting();

    try {
        // 5、初始化默認(rèn)應(yīng)用參數(shù)類
        ApplicationArguments applicationArguments = new DefaultApplicationArguments(
                args);

        // 6、根據(jù)運行監(jiān)聽器和應(yīng)用參數(shù)來準(zhǔn)備 Spring 環(huán)境
        ConfigurableEnvironment environment = prepareEnvironment(listeners,
                applicationArguments);
        configureIgnoreBeanInfo(environment);

        // 7、創(chuàng)建 Banner 打印類
        Banner printedBanner = printBanner(environment);

        // 8、創(chuàng)建應(yīng)用上下文
        context = createApplicationContext();

        // 9、準(zhǔn)備異常報告器
        exceptionReporters = getSpringFactoriesInstances(
                SpringBootExceptionReporter.class,
                new Class[] { ConfigurableApplicationContext.class }, context);

        // 10、準(zhǔn)備應(yīng)用上下文
        prepareContext(context, environment, listeners, applicationArguments,
                printedBanner);

        // 11、刷新應(yīng)用上下文
        refreshContext(context);

        // 12、應(yīng)用上下文刷新后置處理
        afterRefresh(context, applicationArguments);

        // 13、停止計時監(jiān)控類
        stopWatch.stop();

        // 14、輸出日志記錄執(zhí)行主類名、時間信息
        if (this.logStartupInfo) {
            new StartupInfoLogger(this.mainApplicationClass)
                    .logStarted(getApplicationLog(), stopWatch);
        }

        // 15、發(fā)布應(yīng)用上下文啟動完成事件
        listeners.started(context);

        // 16、執(zhí)行所有 Runner 運行器
        callRunners(context, applicationArguments);
    }
    catch (Throwable ex) {
        handleRunFailure(context, ex, exceptionReporters, listeners);
        throw new IllegalStateException(ex);
    }

    try {
        // 17、發(fā)布應(yīng)用上下文就緒事件
        listeners.running(context);
    }
    catch (Throwable ex) {
        handleRunFailure(context, ex, exceptionReporters, null);
        throw new IllegalStateException(ex);
    }

    // 18、返回應(yīng)用上下文
    return context;
}

所以,我們可以按以下幾步來分解 run方法的啟動過程。

1、創(chuàng)建并啟動計時監(jiān)控類

StopWatch stopWatch = new StopWatch();
stopWatch.start();

來看下這個計時監(jiān)控類 StopWatch 的相關(guān)源碼:

public void start() throws IllegalStateException {
    start("");
}

public void start(String taskName) throws IllegalStateException {
    if (this.currentTaskName != null) {
        throw new IllegalStateException("Can't start StopWatch: it's already running");
    }
    this.currentTaskName = taskName;
    this.startTimeMillis = System.currentTimeMillis();
}

首先記錄了當(dāng)前任務(wù)的名稱,默認(rèn)為空字符串,然后記錄當(dāng)前 Spring Boot 應(yīng)用啟動的開始時間。
2、初始化應(yīng)用上下文和異常報告集合

ConfigurableApplicationContext context = null;
Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();

3、設(shè)置系統(tǒng)屬性 java.awt.headless 的值

configureHeadlessProperty();

設(shè)置該默認(rèn)值為:true,Java.awt.headless = true 有什么作用?

對于一個 Java 服務(wù)器來說經(jīng)常要處理一些圖形元素,例如地圖的創(chuàng)建或者圖形和圖表等。這些API基本上總是需要運行一個X-server以便能使用AWT(Abstract Window Toolkit,抽象窗口工具集)。然而運行一個不必要的 X-server 并不是一種好的管理方式。有時你甚至不能運行 X-server,因此最好的方案是運行 headless 服務(wù)器,來進行簡單的圖像處理。

參考:www.cnblogs.com/princessd8251/p/4000016.html

4、創(chuàng)建所有 Spring 運行監(jiān)聽器并發(fā)布應(yīng)用啟動事件

SpringApplicationRunListeners listeners = getRunListeners(args);
listeners.starting();

來看下創(chuàng)建 Spring 運行監(jiān)聽器相關(guān)的源碼:


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

SpringApplicationRunListeners(Log log,
        Collection<? extends SpringApplicationRunListener> listeners) {
    this.log = log;
    this.listeners = new ArrayList<>(listeners);
}

創(chuàng)建邏輯和之前實例化初始化器和監(jiān)聽器的一樣,一樣調(diào)用的是 getSpringFactoriesInstances 方法來獲取配置的監(jiān)聽器名稱并實例化所有的類。

SpringApplicationRunListener 所有監(jiān)聽器配置在 spring-boot-2.0.3.RELEASE.jar!/META-INF/spring.factories 這個配置文件里面。

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

5、初始化默認(rèn)應(yīng)用參數(shù)類

ApplicationArguments applicationArguments = new DefaultApplicationArguments(
        args);

6、根據(jù)運行監(jiān)聽器和應(yīng)用參數(shù)來準(zhǔn)備 Spring 環(huán)境

ConfigurableEnvironment environment = prepareEnvironment(listeners,
        applicationArguments);
configureIgnoreBeanInfo(environment);

下面我們主要來看下準(zhǔn)備環(huán)境的 prepareEnvironment 源碼:

private ConfigurableEnvironment prepareEnvironment(
        SpringApplicationRunListeners listeners,
        ApplicationArguments applicationArguments) {
    // 6.1) 獲?。ɑ蛘邉?chuàng)建)應(yīng)用環(huán)境
    ConfigurableEnvironment environment = getOrCreateEnvironment();

    // 6.2) 配置應(yīng)用環(huán)境
    configureEnvironment(environment, applicationArguments.getSourceArgs());
    listeners.environmentPrepared(environment);
    bindToSpringApplication(environment);
    if (this.webApplicationType == WebApplicationType.NONE) {
        environment = new EnvironmentConverter(getClassLoader())
                .convertToStandardEnvironmentIfNecessary(environment);
    }
    ConfigurationPropertySources.attach(environment);
    return environment;
}
  • 6.1 獲?。ɑ蛘邉?chuàng)建)應(yīng)用環(huán)境
private ConfigurableEnvironment getOrCreateEnvironment() {
    if (this.environment != null) {
        return this.environment;
    }
    if (this.webApplicationType == WebApplicationType.SERVLET) {
        return new StandardServletEnvironment();
    }
    return new StandardEnvironment();
}

這里分為標(biāo)準(zhǔn) Servlet 環(huán)境和標(biāo)準(zhǔn)環(huán)境。

  • 6.2 配置應(yīng)用環(huán)境
protected void configureEnvironment(ConfigurableEnvironment environment,
        String[] args) {
    configurePropertySources(environment, args);
    configureProfiles(environment, args);
}

這里分為以下兩步來配置應(yīng)用環(huán)境。

  • 配置 property sources
  • 配置 Profiles

這里主要處理所有 property sources 配置和 profiles 配置。

7、創(chuàng)建 Banner 打印類

Banner printedBanner = printBanner(environment);

這是用來打印 Banner 的處理類,這個沒什么好說的。

8、創(chuàng)建應(yīng)用上下文

context = createApplicationContext();

來看下 createApplicationContext() 方法的源碼:

protected ConfigurableApplicationContext createApplicationContext() {
    Class<?> contextClass = this.applicationContextClass;
    if (contextClass == null) {
        try {
            switch (this.webApplicationType) {
            case SERVLET:
                contextClass = Class.forName(DEFAULT_WEB_CONTEXT_CLASS);
                break;
            case REACTIVE:
                contextClass = Class.forName(DEFAULT_REACTIVE_WEB_CONTEXT_CLASS);
                break;
            default:
                contextClass = Class.forName(DEFAULT_CONTEXT_CLASS);
            }
        }
        catch (ClassNotFoundException ex) {
            throw new IllegalStateException(
                    "Unable create a default ApplicationContext, "
                            + "please specify an ApplicationContextClass",
                    ex);
        }
    }
    return (ConfigurableApplicationContext) BeanUtils.instantiateClass(contextClass);
}

其實就是根據(jù)不同的應(yīng)用類型初始化不同的上下文應(yīng)用類。

9、準(zhǔn)備異常報告器

exceptionReporters = getSpringFactoriesInstances(
        SpringBootExceptionReporter.class,
        new Class[] { ConfigurableApplicationContext.class }, context);

邏輯和之前實例化初始化器和監(jiān)聽器的一樣,一樣調(diào)用的是 getSpringFactoriesInstances 方法來獲取配置的異常類名稱并實例化所有的異常處理類。

該異常報告處理類配置在 spring-boot-2.0.3.RELEASE.jar!/META-INF/spring.factories 這個配置文件里面。

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

10、準(zhǔn)備應(yīng)用上下文

prepareContext(context, environment, listeners, applicationArguments,
        printedBanner);

來看下 prepareContext() 方法的源碼:

private void prepareContext(ConfigurableApplicationContext context,
        ConfigurableEnvironment environment, SpringApplicationRunListeners listeners,
        ApplicationArguments applicationArguments, Banner printedBanner) {
    // 10.1)綁定環(huán)境到上下文
    context.setEnvironment(environment);

    // 10.2)配置上下文的 bean 生成器及資源加載器
    postProcessApplicationContext(context);

    // 10.3)為上下文應(yīng)用所有初始化器
    applyInitializers(context);

    // 10.4)觸發(fā)所有 SpringApplicationRunListener 監(jiān)聽器的 contextPrepared 事件方法
    listeners.contextPrepared(context);

    // 10.5)記錄啟動日志
    if (this.logStartupInfo) {
        logStartupInfo(context.getParent() == null);
        logStartupProfileInfo(context);
    }

    // 10.6)注冊兩個特殊的單例bean
    context.getBeanFactory().registerSingleton("springApplicationArguments",
            applicationArguments);
    if (printedBanner != null) {
        context.getBeanFactory().registerSingleton("springBootBanner", printedBanner);
    }

    // 10.7)加載所有資源
    Set<Object> sources = getAllSources();
    Assert.notEmpty(sources, "Sources must not be empty");
    load(context, sources.toArray(new Object[0]));

    // 10.8)觸發(fā)所有 SpringApplicationRunListener 監(jiān)聽器的 contextLoaded 事件方法
    listeners.contextLoaded(context);
}

11、刷新應(yīng)用上下文

refreshContext(context);

這個主要是刷新 Spring 的應(yīng)用上下文,源碼如下,不詳細(xì)說明。

private void refreshContext(ConfigurableApplicationContext context) {
    refresh(context);
    if (this.registerShutdownHook) {
        try {
            context.registerShutdownHook();
        }
        catch (AccessControlException ex) {
            // Not allowed in some environments.
        }
    }
}

12、應(yīng)用上下文刷新后置處理

afterRefresh(context, applicationArguments);

看了下這個方法的源碼是空的,目前可以做一些自定義的后置處理操作。

/**
 * Called after the context has been refreshed.
 * @param context the application context
 * @param args the application arguments
 */
protected void afterRefresh(ConfigurableApplicationContext context,
        ApplicationArguments args) {
}

13、停止計時監(jiān)控類

stopWatch.stop();
public void stop() throws IllegalStateException {
    if (this.currentTaskName == null) {
        throw new IllegalStateException("Can't stop StopWatch: it's not running");
    }
    long lastTime = System.currentTimeMillis() - this.startTimeMillis;
    this.totalTimeMillis += lastTime;
    this.lastTaskInfo = new TaskInfo(this.currentTaskName, lastTime);
    if (this.keepTaskList) {
        this.taskList.add(this.lastTaskInfo);
    }
    ++this.taskCount;
    this.currentTaskName = null;
}
```java
計時監(jiān)聽器停止,并統(tǒng)計一些任務(wù)執(zhí)行信息。

**14、輸出日志記錄執(zhí)行主類名、時間信息**
```java
if (this.logStartupInfo) {
    new StartupInfoLogger(this.mainApplicationClass)
            .logStarted(getApplicationLog(), stopWatch);
}

15、發(fā)布應(yīng)用上下文啟動完成事件

listeners.started(context);

觸發(fā)所有 SpringApplicationRunListener 監(jiān)聽器的 started 事件方法。

16、執(zhí)行所有 Runner 運行器

callRunners(context, applicationArguments);
private void callRunners(ApplicationContext context, ApplicationArguments args) {
    List<Object> runners = new ArrayList<>();
    runners.addAll(context.getBeansOfType(ApplicationRunner.class).values());
    runners.addAll(context.getBeansOfType(CommandLineRunner.class).values());
    AnnotationAwareOrderComparator.sort(runners);
    for (Object runner : new LinkedHashSet<>(runners)) {
        if (runner instanceof ApplicationRunner) {
            callRunner((ApplicationRunner) runner, args);
        }
        if (runner instanceof CommandLineRunner) {
            callRunner((CommandLineRunner) runner, args);
        }
    }
}

執(zhí)行所有 ApplicationRunnerCommandLineRunner 這兩種運行器,不詳細(xì)展開了。

17、發(fā)布應(yīng)用上下文就緒事件
listeners.running(context);
觸發(fā)所有 SpringApplicationRunListener 監(jiān)聽器的 running 事件方法。

18、返回應(yīng)用上下文

return context;

總結(jié)

Spring Boot 的啟動全過程源碼分析至此,分析 Spring 源碼真是一個痛苦的過程,希望能給大家提供一點參考和思路,也希望能給正在 Spring Boot 學(xué)習(xí)路上的朋友一點收獲。


原文地址1:
http://mp.weixin.qq.com/s?__biz=MzI3ODcxMzQzMw==&mid=2247486661&idx=1&sn=ef3308c7a392cb01e3788fd183ee0eff&chksm=eb5389f3dc2400e5a258b338dca36f7d20b46393daa494234ba1b706787413b861cdbc73197f&scene=21#wechat_redirect

原文地址2:
https://mp.weixin.qq.com/s?__biz=MzI3ODcxMzQzMw%3D%3D&mid=2247486739&idx=1&sn=174827f0ff5fb6c999e65ee80266bc39#wechat_redirect

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容