Spring Boot 2.x 啓動全過程源碼分析(上)入口類剖析

Spring Boot 的應用教程我們已經分享過很多了,今天來通過源碼來分析下它的啓動過程,探究下 Spring Boot 爲什麼這麼簡便的奧祕。

本篇基於 Spring Boot 2.0.3 版本進行分析,閱讀本文需要有一些 Java 和 Spring 框架基礎,如果還不知道 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 方法調用關係源碼:

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);
}

第一個參數 primarySource:加載的主要資源類

第二個參數 args:傳遞給應用的應用參數

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

SpringApplication 的實例化過程

Spring Boot 2.x 啓動全過程源碼分析(上)入口類剖析

接着上面的 SpringApplication 構造方法進入以下源碼:

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、推斷當前 WEB 應用類型
    this.webApplicationType = deduceWebApplicationType();

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

    // 6、設置監聽器          
    setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));

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

可知這個構造器類的初始化包括以下 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、推斷當前 WEB 應用類型

this.webApplicationType = deduceWebApplicationType();

來看下 deduceWebApplicationType 方法和相關的源碼:

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,

    /**
     * 響應式 WEB 項目
     */
    REACTIVE

}

這個就是根據類路徑下是否有對應項目類型的類推斷出不同的應用類型。

5、設置應用上線文初始化器

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 應用上下文,如註冊屬性資源、激活 Profiles 等。

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

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

再來看下這個初始化 getSpringFactoriesInstances 方法和相關的源碼:

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;
}

設置應用上下文初始化器可分爲以下 5 個步驟。

5.1)獲取當前線程上下文類加載器

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

5.2)獲取 ApplicationContextInitializer 的實例名稱集合並去重

Set<String> names = new LinkedHashSet<>(
                SpringFactoriesLoader.loadFactoryNames(type, classLoader));

loadFactoryNames 方法相關的源碼如下:

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);
    }
}

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

spring-boot-autoconfigure-2.0.3.RELEASE.jar!/META-INF/spring.factories 的初始化器相關配置內容如下:

# Initializers
org.springframework.context.ApplicationContextInitializer=\
org.springframework.boot.autoconfigure.SharedMetadataReaderFactoryContextInitializer,\
org.springframework.boot.autoconfigure.logging.ConditionEvaluationReportLoggingListener

5.3)根據以上類路徑創建初始化器實例列表

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、設置監聽器

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 接口,實現了觀察者模式,它一般用來定義感興趣的事件類型,事件類型限定於 ApplicationEvent 的子類,這同樣繼承了 JDK 的 java.util.EventObject 接口。

設置監聽器和設置初始化器調用的方法是一樣的,只是傳入的類型不一樣,設置監聽器的接口類型爲:getSpringFactoriesInstances,對應的 spring-boot-autoconfigure-2.0.3.RELEASE.jar!/META-INF/spring.factories 文件配置內容請見下方。

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

可以看出目前只有一個 BackgroundPreinitializer 監聽器。

7、推斷主入口應用類

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;
}

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

總結

源碼分析內容有點多,也很麻煩,本章暫時分析到 SpringApplication 構造方法的初始化流程,下章再繼續分析其 run 方法,作者很快寫完過兩天就發佈,掃碼關注下面的公衆號 "Java技術棧" 即可獲取推送更新。

image

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章