SpringBoot 源碼分析—SpringBoot啟動過程

DemoApplication.java代碼如下

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

現(xiàn)在來分析一下SpringApplication.run執(zhí)行的流程:


圖片.png
  • 1.創(chuàng)建了一個SpringApplication實例,并作為參數(shù)傳遞了主配置類
  • 2.調(diào)用了SpringApplication.run(args)方法
  1. 創(chuàng)建實例
    public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
        // 設(shè)置resourceLoader
        this.resourceLoader = resourceLoader;

        // 斷言資源類不能為null
        Assert.notNull(primarySources, "PrimarySources must not be null");

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

        // >>> 1.推斷當前應(yīng)用的類型(根據(jù)當前classpath下是否包含某些類來確定)
        this.webApplicationType = WebApplicationType.deduceFromClasspath();

        // >>> 2.設(shè)置初始化器(從spring.factories獲取ApplicationContextInitializer獲取配置的類)
        setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));

        // >>> 3.設(shè)置監(jiān)聽器(從spring.factories中獲取ApplicationListener配置的類)
        setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));

        // >>> 4.推斷MainApplicationClass(當前main方法所在的Class)
        this.mainApplicationClass = deduceMainApplicationClass();
    }
  1. run方法
   /**
     * Run the Spring application, creating and refreshing a new
     * {@link ApplicationContext}.
     * @param args the application arguments (usually passed from a Java main method)
     * @return a running {@link ApplicationContext}
     */
    public ConfigurableApplicationContext run(String... args) {
        // 應(yīng)用啟動時間記錄器
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();


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

        // 1.獲取監(jiān)聽器并觸發(fā)事件(從spring.factories中獲取SpringApplicationRunListener配置的類,并初始化作為監(jiān)聽器)
        // SpringApplicationRunListener負責在SpringBootApplication的不同生命周期廣播出不同的事件,傳遞給ApplicationListener
        SpringApplicationRunListeners listeners = getRunListeners(args);
        // 觸發(fā)
        listeners.starting();

        try {
            // 2.初始化環(huán)境
            ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
            ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
            configureIgnoreBeanInfo(environment);
            Banner printedBanner = printBanner(environment);

            // 3.創(chuàng)建應(yīng)用上下文對象,初始化IOC容器(ioc容器創(chuàng)建后作為一個屬性存在context中)
            context = createApplicationContext();

            // 取到關(guān)于SpringBoot異常報告的一些報告器
            exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,
                    new Class[] { ConfigurableApplicationContext.class }, context);

            // 4.刷新IOC容器前的處理
            prepareContext(context, environment, listeners, applicationArguments, printedBanner);

            // 5.刷新IOC容器,
            // 調(diào)用IOC容器的refresh,觸發(fā)invokeBeanFactoryPostProcessors(),此步驟中
            // 會調(diào)用ConfigurationClassParser.parse去解析主配置類(啟動類),識別ComponentScan等注解來解析配置類
            refreshContext(context);

            // 6.刷新IOC容器后的處理
            afterRefresh(context, applicationArguments);
            stopWatch.stop();
            if (this.logStartupInfo) {
                new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
            }
            listeners.started(context);
            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;
    }

核心步驟:

  • 1、獲取RunListener并啟動這些監(jiān)聽器
// 1.獲取監(jiān)聽器并觸發(fā)事件(從spring.factories中獲取SpringApplicationRunListener配置的類,并初始化作為監(jiān)聽器)
// SpringApplicationRunListener負責在SpringBootApplication的不同生命周期廣播出不同的事件,傳遞給ApplicationListener
  SpringApplicationRunListeners listeners = getRunListeners(args);
  listeners.starting();

什么是RunListener呢,我們看下getRunListeners方法:

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

核心代碼是getSpringFactoriesInstances(SpringApplicationRunListener.class, types, this, args);
繼續(xù)看這個方法源碼

    private <T> Collection<T> getSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes, Object... args) {
        ClassLoader classLoader = getClassLoader();
        // 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;
    }

其核心代碼是SpringFactoriesLoader.loadFactoryNames(type, classLoader);
再看這個loadFactoryNames方法:

圖片.png

注釋已經(jīng)說明了本方法的作用,通過給定的類加載器從FACTORY_RESOURCE_LOCATION這個位置去加載指定的工廠類型
如圖中箭頭指向所示:

  • 1、先調(diào)用了重載方法loadSpringFactories(ClassLoader classloader)
  • 2、重載方法中從指定路徑(META-INF/spring.factories)中加載所有類全限定名
  • 3、通過傳入的工廠類型名稱,取出本次需要(指定類型)的工廠類型名稱集合

那么,這里就是加載所有的SpringApplicationRunListener所配置的類集合,我們從META-INF/spring.factories中找到這個SpringApplicationRunListener


idea查找spring.factories.png

可以看到搜索文件時,會顯示很多個spring.factories,很多jar中都有這個路徑的資源文件。實質(zhì)上,springboot會加載每個jar中的spring.factories中的內(nèi)容,這也就是starter擴展機制,我們自定義starter時,只需要在自己的jar中的META-INF/spring.factories中配置上自己的。


spring-boot中spring.factories.png

可以看到這個spring.factories中有很多個KEY=VALUE的配置,其格式與properties并無二致,每個KEY都是一個接口,VALUE對應(yīng)一個字符串, VALUE中多個類全限定名用逗號分割,每個全限定名對應(yīng)的類都是KEY這個接口的實現(xiàn)類(直接或間接實現(xiàn))。

SpringApplicationRunListener.png

SpringApplicationRunListener:
其注釋已經(jīng)說得比較清楚了:監(jiān)聽SpringApplication的run方法。

至此,SpringApplication.run(ClassLoader classLoader)中的第一步,獲取監(jiān)聽器并執(zhí)行分析結(jié)束。

  • 2、初始化環(huán)境
            // 2.初始化環(huán)境
            ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
            ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
            configureIgnoreBeanInfo(environment);
            Banner printedBanner = printBanner(environment);

這一步主要是環(huán)境準備工作:

  • 2.1 參數(shù)提取,將args中的參數(shù)重新包裝為ApplicationArguments
  • 2.2 準備環(huán)境
    private ConfigurableEnvironment prepareEnvironment(SpringApplicationRunListeners listeners,
            ApplicationArguments applicationArguments) {
        // Create and configure the environment
        // 根據(jù)應(yīng)用類型創(chuàng)建相應(yīng)的環(huán)境對象
        ConfigurableEnvironment environment = getOrCreateEnvironment();

        // 配置一些屬性,包括解析args參數(shù),設(shè)置activeProfiles等
        configureEnvironment(environment, applicationArguments.getSourceArgs());
        ConfigurationPropertySources.attach(environment);

        // 觸發(fā)監(jiān)聽器,包括ConfigFileApplicationListener會在這一步根據(jù)配置文件位置找到對應(yīng)的配置文件并加載到environment中
        listeners.environmentPrepared(environment);
        bindToSpringApplication(environment);
        if (!this.isCustomEnvironment) {
            environment = new EnvironmentConverter(getClassLoader()).convertEnvironmentIfNecessary(environment,
                    deduceEnvironmentClass());
        }
        ConfigurationPropertySources.attach(environment);
        return environment;
    }

  • 2.3 配置忽略的bean信息
    private void configureIgnoreBeanInfo(ConfigurableEnvironment environment) {
        if (System.getProperty(CachedIntrospectionResults.IGNORE_BEANINFO_PROPERTY_NAME) == null) {
            Boolean ignore = environment.getProperty("spring.beaninfo.ignore", Boolean.class, Boolean.TRUE);
            System.setProperty(CachedIntrospectionResults.IGNORE_BEANINFO_PROPERTY_NAME, ignore.toString());
        }
    }
  • 2.4 打印Banner
    private Banner printBanner(ConfigurableEnvironment environment) {
        if (this.bannerMode == Banner.Mode.OFF) {
            return null;
        }
        ResourceLoader resourceLoader = (this.resourceLoader != null) ? this.resourceLoader
                : new DefaultResourceLoader(getClassLoader());
        SpringApplicationBannerPrinter bannerPrinter = new SpringApplicationBannerPrinter(resourceLoader, this.banner);
        if (this.bannerMode == Mode.LOG) {
            return bannerPrinter.print(environment, this.mainApplicationClass, logger);
        }
        return bannerPrinter.print(environment, this.mainApplicationClass, System.out);
    }

SpringBoot項目中,默認會打印springboot的banner,當然我們可以通過"spring.banner.image.location"或者"spring.banner.location"來配置我們自己的項目banner

3.創(chuàng)建applicationContext

    /**
     * Strategy method used to create the {@link ApplicationContext}. By default this
     * method will respect any explicitly set application context or application context
     * class before falling back to a suitable default.
     * @return the application context (not yet refreshed)
     * @see #setApplicationContextClass(Class)
     */
    protected ConfigurableApplicationContext createApplicationContext() {
        // 獲取class
        Class<?> contextClass = this.applicationContextClass;
        if (contextClass == null) {
            try {
                switch (this.webApplicationType) {
                case SERVLET:
                    contextClass = Class.forName(DEFAULT_SERVLET_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);
            }
        }

        // 創(chuàng)建ApplicationContext實例
        return (ConfigurableApplicationContext) BeanUtils.instantiateClass(contextClass);
    }

根據(jù)應(yīng)用類型,實例化相應(yīng)的applicationContext。

4 刷新IOC容器前的處理

/**
     * 完成相關(guān)屬性的設(shè)置
     * 完成一些bean的創(chuàng)建
     * @param context
     * @param environment
     * @param listeners
     * @param applicationArguments
     * @param printedBanner
     */
    private void prepareContext(ConfigurableApplicationContext context, ConfigurableEnvironment environment,
            SpringApplicationRunListeners listeners, ApplicationArguments applicationArguments, Banner printedBanner) {
        // 設(shè)置環(huán)境到上下文中
        context.setEnvironment(environment);

        // 設(shè)置一些屬性
        postProcessApplicationContext(context);

        // 遍歷初始化器并執(zhí)行
        applyInitializers(context);

        // 執(zhí)行一些監(jiān)聽器
        listeners.contextPrepared(context);
        if (this.logStartupInfo) {
            logStartupInfo(context.getParent() == null);
            logStartupProfileInfo(context);
        }

        // Add boot specific singleton beans
        ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
        beanFactory.registerSingleton("springApplicationArguments", applicationArguments);
        if (printedBanner != null) {
            beanFactory.registerSingleton("springBootBanner", printedBanner);
        }
        if (beanFactory instanceof DefaultListableBeanFactory) {
            ((DefaultListableBeanFactory) beanFactory)
                    .setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);
        }
        if (this.lazyInitialization) {
            context.addBeanFactoryPostProcessor(new LazyInitializationBeanFactoryPostProcessor());
        }

        // Load the sources
        Set<Object> sources = getAllSources();
        Assert.notEmpty(sources, "Sources must not be empty");

        // 將主啟動類定義加載到IOC容器beanDefinitionMap中
        load(context, sources.toArray(new Object[0]));

        // 發(fā)布一些事件
        listeners.contextLoaded(context);
    }

5. 刷新IOC容器

     private void refreshContext(ConfigurableApplicationContext context) {
        if (this.registerShutdownHook) {
            try {
                context.registerShutdownHook();
            }
            catch (AccessControlException ex) {
                // Not allowed in some environments.
            }
        }
        refresh(context);
    }
    /**
     * Refresh the underlying {@link ApplicationContext}.
     * @param applicationContext the application context to refresh
     */
    protected void refresh(ApplicationContext applicationContext) {
        Assert.isInstanceOf(AbstractApplicationContext.class, applicationContext);
        ((AbstractApplicationContext) applicationContext).refresh();
    }

最終調(diào)用applicationContext.refresh(),這里就回到了spring中ioc容器的refresh方法。
applicationContext.refresh中,會執(zhí)行invokeBeanFactoryPostProcessors(),
此步驟中會調(diào)用ConfigurationClassParser.parse去解析主配置類(啟動類),識別ComponentScan等注解并完成配置。

6.刷新IOC容器后的處理

    /**
     * Called after the context has been refreshed.
     * @param context the application context
     * @param args the application arguments
     */
    protected void afterRefresh(ConfigurableApplicationContext context, ApplicationArguments args) {
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容