SpringBoot源碼解析 -- SpringBoot啓動過程

源碼分析基於spring boot 2.1java

本文經過閱讀源碼,分析SpringBoot的啓動過程。web

先看一個例子spring

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

例子很簡單,本文主要關注三個問題緩存

  1. SpringApplication#run方法的做用
  2. SpringApplication#run方法中MyApplication.class參數的做用
  3. SpringApplication#run方法中args參數的做用

SpringApplication#run微信

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

先構造SpringApplication實例,再調用run方法app

SpringApplication#構造方法less

public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
    this.resourceLoader = resourceLoader;

    this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));     // #1
    this.webApplicationType = WebApplicationType.deduceFromClasspath();    //#2
    setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));    //#3
    setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class)); //#4
    this.mainApplicationClass = deduceMainApplicationClass();    // #5
}

#1 設置SpringApplication#primarySources,注意這裏primarySources參數就是run方法的第一個參數
#2 判斷當前應用是JAVA應用,SERVLET應用或REACTIVE應用。
#3 加載spring.factories中配置的ApplicationContextInitializer實現類,將結果存放到SpringApplication#initializers
#4 加載spring.factories中配置的ApplicationListener實現類,將結果存放到SpringApplication#listeners
#5 獲取main方法所在Class源碼分析

SpringApplication#getSpringFactoriesInstances -> SpringFactoriesLoader#loadSpringFactoriespost

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));    //#1
        result = new LinkedMultiValueMap<>();
        while (urls.hasMoreElements()) {
            URL url = urls.nextElement();
            UrlResource resource = new UrlResource(url);
            Properties properties = PropertiesLoaderUtils.loadProperties(resource);    //#2
            for (Map.Entry<?, ?> entry : properties.entrySet()) {
                String factoryClassName = ((String) entry.getKey()).trim();
                for (String factoryName : StringUtils.commaDelimitedListToStringArray((String) entry.getValue())) {
                    result.add(factoryClassName, factoryName.trim());    //#3
                }
            }
        }
        cache.put(classLoader, result);
        return result;
    }
    catch (IOException ex) {
        throw new IllegalArgumentException("Unable to load factories from location [" +
                FACTORIES_RESOURCE_LOCATION + "]", ex);
    }
}

#1 FACTORIES_RESOURCE_LOCATION就是字符串"META-INF/spring.factories",這裏讀取jar中META-INF/spring.factories文件內容
#2 加載spring.factories文件(格式爲Properties)
#3 讀取Properties內容,緩存結果this

spring.factories格式爲

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

key爲spring擴展接口(或聲明功能的註解),value爲對應的功能實現類的列表

SpringApplication#run

public ConfigurableApplicationContext run(String... args) {
    StopWatch stopWatch = new StopWatch();    // #1
    stopWatch.start();
    ConfigurableApplicationContext context = null;
    Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
    configureHeadlessProperty();    // #2
    SpringApplicationRunListeners listeners = getRunListeners(args);    // #3
    listeners.starting();    // #4
    try {
        ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);    // #5
        ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);    // #6
        configureIgnoreBeanInfo(environment);    // #7
        Banner printedBanner = printBanner(environment);
        context = createApplicationContext();    // #8
        exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,
                new Class[] { ConfigurableApplicationContext.class }, context);
        prepareContext(context, environment, listeners, applicationArguments, printedBanner);    // #9
        refreshContext(context);    // #10
        afterRefresh(context, applicationArguments);    // #11
        stopWatch.stop();
        if (this.logStartupInfo) {
            new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
        }
        listeners.started(context);    // #12
        callRunners(context, applicationArguments);    // #13
    }
    catch (Throwable ex) {
        handleRunFailure(context, ex, exceptionReporters, listeners);
        throw new IllegalStateException(ex);
    }

    try {
        listeners.running(context);    // #14
    }
    catch (Throwable ex) {
        handleRunFailure(context, ex, exceptionReporters, null);
        throw new IllegalStateException(ex);
    }
    return context;
}

#1 開始計時(計算初始化須要花費多少時間)
#2 配置java.awt.headless
#3 獲取spring.factories中配置的SpringApplicationRunListener實現類
SpringApplicationRunListeners是SpringApplicationRunListener的組合,SpringApplicationRunListener是SpringBoot中新增接口,經過它來間接調用 ApplicationListener。
該接口實現類爲EventPublishingRunListener,他的構造方法中需傳入SpringApplication,並獲取SpringApplication#listeners屬性。
SpringApplicationRunListener組件很重要,SpringBoot中不少擴展也是經過listerner實現的,如日誌系統的啓動
#4 發送ApplicationStartedEvent事件
#5 命令行參數處理
#6 構建Environment
#7 處理spring.beaninfo.ignore配置
#8 建立ApplicationContext
#9 prepareContext
#10 refreshContext
#11 afterRefresh,預留擴展方法
#12 發送ApplicationStartedEvent事件
#13 運行ApplicationRunner,CommandLineRunner
#14 發送ApplicationReadyEvent事件

SpringApplication#prepareEnvironment

private ConfigurableEnvironment prepareEnvironment(SpringApplicationRunListeners listeners,
        ApplicationArguments applicationArguments) {
    ConfigurableEnvironment environment = getOrCreateEnvironment();    // #1
    configureEnvironment(environment, applicationArguments.getSourceArgs());    // #2
    ConfigurationPropertySources.attach(environment);
    listeners.environmentPrepared(environment);    // #3
    bindToSpringApplication(environment);
    if (!this.isCustomEnvironment) {
        environment = new EnvironmentConverter(getClassLoader()).convertEnvironmentIfNecessary(environment,
                deduceEnvironmentClass());
    }
    ConfigurationPropertySources.attach(environment);
    return environment;
}

#1 建立一個Environment
#2 將SpringApplication#run中的可變參數列表傳遞給Environment
回到文章開頭說的第3個問題,關於MyApplication#run中的args參數
咱們在啓動SpringBoot時,能夠添加命令行參數,如java -jar MyApplication.jar --spring.profiles.active=dev
命令行參數--spring.profiles.active=dev會傳遞給main方法,main方法中須要將其傳遞給SpringApplication#run方法,
這裏將命令行參數添加Environment中,做爲一個PropertySource。
必須在main方法中將args參數傳給SpringApplication#run方法,不然會形成命令行的參數失效。
#3 發送ApplicationEnvironmentPreparedEvent事件

SpringApplication#createApplicationContext

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

#1 SERVLET應用,選擇AnnotationConfigServletWebServerApplicationContext
#2 REACTIVE應用,選擇AnnotationConfigReactiveWebServerApplicationContext
#3 JAVA應用,選擇AnnotationConfigApplicationContext
#4 構造對應的Spring Context
**AnnotationConfigServletWebServerApplicationContext#構造方法 -> AnnotatedBeanDefinitionReader#構造方法 ->
AnnotationConfigUtils#registerAnnotationConfigProcessors**
這裏註冊一些實現SpringBoot功能必須的PostProcessor

public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(
        BeanDefinitionRegistry registry, @Nullable Object source) {

    DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);
    if (beanFactory != null) {
        if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) {
            beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);
        }
        if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) {
            beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());
        }
    }

    Set<BeanDefinitionHolder> beanDefs = new LinkedHashSet<>(8);

    if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {
        RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);    //#1
        def.setSource(source);
        beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME));
    }

    if (!registry.containsBeanDefinition(AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
        RootBeanDefinition def = new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class);    //#2
        def.setSource(source);
        beanDefs.add(registerPostProcessor(registry, def, AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
    }

    ...

    return beanDefs;
}

#1 註冊ConfigurationClassPostProcessor,該PostProcessor處理@Configuration等註解
#2 註冊AutowiredAnnotationBeanPostProcessor,該PostProcessor處理@Value,@Autowired等註解

SpringApplication#prepareContext

private void prepareContext(ConfigurableApplicationContext context, ConfigurableEnvironment environment,
        SpringApplicationRunListeners listeners, ApplicationArguments applicationArguments, Banner printedBanner) {
    context.setEnvironment(environment);    
    postProcessApplicationContext(context);
    applyInitializers(context);    //#1
    listeners.contextPrepared(context);    //#2
    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);
    }
    // Load the sources
    Set<Object> sources = getAllSources();
    Assert.notEmpty(sources, "Sources must not be empty");
    load(context, sources.toArray(new Object[0]));    //#3
    listeners.contextLoaded(context);    //#4
}

#1 調用ApplicationContextInitializer#initialize
#2 調用SpringApplicationRunListener#contextPrepared方法
#3 getAllSources獲取primarySources以及全部的PropertySource,並解析爲BeanDefinition註冊到Spring上下文中(後面要使用)
PropertySource(屬性源)用於Environment從新獲取配置屬性。
primarySources就是SpringApplication#run方法的第一個參數
回到文章開頭第2個問題,
經過SpringApplication#run方法的MyApplication.class參數,這裏將MyApplication的BeanDefinition註冊到Spring上下文中,後面Spring就是能夠獲取MyApplication上的@SpringBootApplication等註解了。
#4 發送ApplicationContextInitializedEvent事件

SpringApplication#refreshContext
以前spring源碼解析的文章已經說過refreshContext操做了。

SpringApplication#callRunners

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

#1 獲取ApplicationRunner和CommandLineRunner
#2 調用對應的run方法

若是您以爲本文不錯,歡迎關注個人微信公衆號,您的關注是我堅持的動力!

相關文章
相關標籤/搜索