SpringBoot一站式啓動流程源碼分析

1、前言

  由上篇文章咱們得知,SpringBoot啓動時,就是有很簡單的一行代碼。那咱們能夠很清楚的看到這行代碼的主角即是SpringApplication了,本文咱們就來聊一聊這貨,來探尋SpringBoot的一站式啓動流程。html

​  其實SpringApplication 是將一個典型的Spring應用的啓動流程」模板化」了,在沒有特殊定製需求的狀況下,默認的模板化後的執行流程就能知足咱們的需求了。即使是咱們有了特殊的需求也沒有太大關係,SpringApplication在內部合適的啓動節點給咱們提供了一系列不一樣類型的擴展點,咱們就能夠經過這些開放的擴展點來對SpringBoot程序的啓動和關閉過程來進行定製和擴展。vue

2、關於定製

 SpringApplication中提供的最簡單的定製方式當屬設置方法(Setters)定製了。例如,咱們能夠把啓動類改爲以下的方式來擴展啓動行爲:java

@SpringBootApplication
public class DemoApplication {
    public void main(String[] args) {
        // SpringApplication.run(DemoApplication.class, args);
        SpringApplication bootstrap = new SpringApplication(DemoApplication.class);
        bootstrap.setBanner(new Banner() {
            @Override
            public void printBanner(Environment environment, Class<?> aClass, PrintStream printStream) {
                System.out.println("My custom banner...");
            }
        });
        bootstrap.setBannerMode(Bannder.Mode.CONSOLE);
        bootstrap.run(args);
    }
}

​  大多數的狀況下,SpringApplication默認已經提供好了設置,咱們基本不須要再對這些表層進行研究了,對錶象之下的本質纔是咱們最應該探究的課題。web

3、揭祕SpringApplication的執行流程 

  由於啓動程序的代碼中運行的就是SpringApplication的run方法,因此咱們執行流程固然就要從這個run方法開始,先上源碼:spring

public class SpringApplication { 
    public SpringApplication(Object... sources) {
        initialize(sources);
    }
    public static ConfigurableApplicationContext run(Object source, String... args) {
        return run(new Object[] { source }, args);
    }
    public static ConfigurableApplicationContext run(Object[] sources, String[] args) {
        return new SpringApplication(sources).run(args);
    }
}

  能夠看出,啓動時:調用run方法先建立一個SpringApplication對象實例,而後調用建立好的SpringApplication的實例的run方法。在SpringApplication實例化的時候,它又會運行如下代碼:bootstrap

private static final String[] WEB_ENVIRONMENT_CLASSES = { "javax.servlet.Servlet",
            "org.springframework.web.context.ConfigurableWebApplicationContext" };
private void initialize(Object[] sources) {
    if (sources != null && sources.length > 0) {
        this.sources.addAll(Arrays.asList(sources));
    }
    this.webEnvironment = deduceWebEnvironment(); // 1
    setInitializers((Collection) getSpringFactoriesInstances(
                ApplicationContextInitializer.class)); // 2
    setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class)); // 3
    this.mainApplicationClass = deduceMainApplicationClass(); // 4
}
private boolean deduceWebEnvironment() {
    for (String className : WEB_ENVIRONMENT_CLASSES) {
        if (!ClassUtils.isPresent(className, null)) {
            return false;
        }
    }
    return true;
}
private <T> Collection<? extends T> getSpringFactoriesInstances(Class<T> type) {
    return getSpringFactoriesInstances(type, new Class<?>[] {});
}
public void setInitializers( Collection<? extends ApplicationContextInitializer<?>> initializers) {
    this.initializers = new ArrayList<ApplicationContextInitializer<?>>();
    this.initializers.addAll(initializers);
}
public void setListeners(Collection<? extends ApplicationListener<?>> listeners) {
    this.listeners = new ArrayList<ApplicationListener<?>>();
    this.listeners.addAll(listeners);
}
  • 首先運行deduceWebEnvironment方法(代碼中標記1處),該方法的做用是根據classpath裏面是否存在某些特徵類({「javax.servlet.Servlet」, 「org.springframework.web.context.ConfigurableWebApplicationContext」 })來決定是建立一個Web類型的ApplicationContext仍是建立一個標準Standalone類型的ApplicationContext.
  • 使用SpringFactoriesLoader在應用的classpath中查找並加載全部可用的ApplicationContextInitializer(代碼中標記2處)。
  • 使用SpringFactoriesLoader在應用的classpath中查找並加載全部可用的ApplicationListener(代碼中標記3處)。
  • 推斷並設置main方法的定義類(代碼中標記4處)。

  這樣,SpringApplication就完成了實例化而且完成了設置。而後就開始執行SpringApplication實例的run方法的邏輯了:markdown

public ConfigurableApplicationContext run(String... args) {
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    ConfigurableApplicationContext context = null;
    FailureAnalyzers analyzers = null;
    configureHeadlessProperty();
    SpringApplicationRunListeners listeners = getRunListeners(args); // 1
    listeners.starting(); // 2
    try {
        ApplicationArguments applicationArguments = new DefaultApplicationArguments(
                args);
        ConfigurableEnvironment environment = prepareEnvironment(listeners,
                applicationArguments); // 3
        Banner printedBanner = printBanner(environment); // 5
        context = createApplicationContext(); // 6
        analyzers = new FailureAnalyzers(context);
        prepareContext(context, environment, listeners, applicationArguments,
                printedBanner);
        refreshContext(context); // 13
        afterRefresh(context, applicationArguments); // 15
        listeners.finished(context, null); // 16
        stopWatch.stop();
        if (this.logStartupInfo) {
            new StartupInfoLogger(this.mainApplicationClass)
                    .logStarted(getApplicationLog(), stopWatch);
        }
        return context;
    }
    catch (Throwable ex) {
        handleRunFailure(context, listeners, analyzers, ex); // 17
        throw new IllegalStateException(ex);
    }
}
private ConfigurableEnvironment prepareEnvironment( SpringApplicationRunListeners listeners, ApplicationArguments applicationArguments) {
    // Create and configure the environment
    ConfigurableEnvironment environment = getOrCreateEnvironment();
    configureEnvironment(environment, applicationArguments.getSourceArgs());
    listeners.environmentPrepared(environment); // 4
    if (!this.webEnvironment) {
        environment = new EnvironmentConverter(getClassLoader())
                .convertToStandardEnvironmentIfNecessary(environment);
    }
    return environment;
}
private void prepareContext(ConfigurableApplicationContext context, ConfigurableEnvironment environment, SpringApplicationRunListeners listeners, ApplicationArguments applicationArguments, Banner printedBanner) {
    context.setEnvironment(environment); // 7
    postProcessApplicationContext(context); // 8
    applyInitializers(context); // 9
    listeners.contextPrepared(context); // 10
    if (this.logStartupInfo) {
        logStartupInfo(context.getParent() == null);
        logStartupProfileInfo(context);
    }

    // Add boot specific singleton beans
    context.getBeanFactory().registerSingleton("springApplicationArguments",
            applicationArguments);
    if (printedBanner != null) {
        context.getBeanFactory().registerSingleton("springBootBanner", printedBanner);
    }

    // Load the sources
    Set<Object> sources = getSources();
    Assert.notEmpty(sources, "Sources must not be empty");
    load(context, sources.toArray(new Object[sources.size()])); // 11
    listeners.contextLoaded(context); // 12
}
private void refreshContext(ConfigurableApplicationContext context) {
    refresh(context);
    if (this.registerShutdownHook) { // 14
        try {
            context.registerShutdownHook();
        }
        catch (AccessControlException ex) {
            // Not allowed in some environments.
        }
    }
}
  • 該方法中,首先經過SpringFactoriesLoader查找並加載SpringApplicationRunListener(代碼標記1處),而後接着調用它們的started()方法(代碼標記2處),告訴這些SpringApplicationRunListener說:「Hello, SpringBoot應用要開始執行嘍」。
  • 接着,建立和配置當前SpringBoot應用將要使用的Environment(包括配置要使用到的PropertySourceProfile)(代碼標記3處).
  • 而後遍歷全部的SpringApplicationRunListenerenvironmentPrepared()方法,告訴他們:「當前SpringBoot應用使用的Environment已經準備好了哈」(代碼標記4處)。
  • 若是SpringApplication的showBanner屬性爲true的話,則打印banner(這裏是基於Banner.Mode來決定banner的打印行爲)(代碼標記5處)。這個步驟其實咱們不用過多關心,我的感受它的用途純粹是爲了好玩。
  • 根據用戶是否明確設置了applicationContextClass類型以及初始化SpringApplication類階段的推斷結果,決定該爲當前的SpringBoot應用建立什麼類型的ApplicationContext,並完成建立(代碼標記6處)。
  • 而後將以前準備好的Environment設置給建立好的ApplicationContext,供之後使用(代碼標記7處)。
  • 根據條件來決定是否使用自定義的BeanNameGenerator,決定是否使用自定義的ResourceLoader(代碼標記8處)。
  • 完成後,SpringApplication會再次藉助SpringFactoriesLoader查找並加載classpath中全部可用的ApplicationContextInitializer,而後遍歷調用它們的initialize(applicationContext)方法來對已經建立好的ApplicationContext進行進一步的處理(代碼標記9處)。
  • 接着,遍歷全部SpringApplicationRunListenercontextPrepared()方法,通知它們:「SpringBoot應用的ApplicationContext準備好啦哈~」(代碼標記10處)。
  • 很是最要的一步,將以前經過@EnableAutoConfiguration獲取的全部配置類以及其餘形式的IoC容器配置類加載到已經準備完畢的ApplicationContext中(代碼標記11處)。
  • 遍歷全部的SpringApplicationRunListener並調用它們的contextLoaded()方法,告訴全部的SpringApplicationRunListener說:「ApplicationContext裝填完畢啦」(代碼標記12處)。
  • 調用ApplicationContextrefresh()方法,完成IoC容器初始化的最後一步流程(代碼標記13處)。
  • 而後再根據條件來決定是否須要添加ShutdownHook(代碼標記14處)。
  • 查找當前ApplicationContext中是否註冊有ApplicationRunner以及CommandLineRunner,若是有,則遍歷執行它們。
  • 不出意外的狀況下,遍歷全部的SpringApplicationRunListener並執行finished()方法,告訴他們:「啓動大功告成了!」(代碼標記16處),若是整個啓動過程當中出現了異常,則依然調用全部的SpringApplicationRunListenerfinished()方法,這種狀況下會將全部的異常信息一塊兒傳入並處理(代碼標記17處)。

  通過以上的這些步驟之後,一個完整的SpringBoot應用就啓動完畢了!整個過程雖然看起來冗長無比,但其實不少都是一些事件通知的擴展點,若是咱們將這些邏輯暫時的忽略掉的話,那整個SpringBoot應用啓動的邏輯就能夠壓縮到極其精簡的幾步了,以下圖:app

  

  這樣咱們對比之後就會發現,其實SpringApplication提供的這些各類擴展點有點」喧賓奪主」的味道,它們佔據了整個SpringBoot應用啓動邏輯的大部分,除了初始化準備好ApplicationContext,剩下的絕大部分工做均是經過這些擴展點來完成的。less

4、總結

  本文,咱們經過源碼的方式來解析了整個SpringBoot應用程序的啓動過程,咱們發現了大部分工做都是由SpringApplication提供的擴展點來完成的,那咱們下一篇文章就來逐一解析這些擴展點組件,這樣的話,咱們就能夠在須要的時候能夠很輕鬆的爲我所用!ide

相關文章
相關標籤/搜索