Spring boot启动流程源码解析

阅读须知

  • 版本:2.0.4
  • 文章中使用/* */注释的方法会做深入分析

正文

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

这段代码相信大家都很熟悉,spring boot的启动类,我们就以这段代码作为切入点,来分析spring boot的启动流程:
SpringApplication:

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

public static ConfigurableApplicationContext run(Class<?>[] primarySources,
        String[] args) {
    /* 构建SpringApplication并运行,创建并且刷新一个新的ApplicationContext */
    return new SpringApplication(primarySources).run(args);
}

SpringApplication:

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

public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
    this.resourceLoader = resourceLoader;
    Assert.notNull(primarySources, "PrimarySources must not be null");
    this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
    // 判断是否能够成功加载一些关键的类来确认web应用类型,这个类型后面会用到
    this.webApplicationType = deduceWebApplicationType();
    /* 获取并设置Spring上下文初始化器 */
    setInitializers((Collection) getSpringFactoriesInstances(
            ApplicationContextInitializer.class));
    /* 获取并设置Spring应用监听器 */
    setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
    // 追述到应用主类,也就是main方法所在的类
    this.mainApplicationClass = deduceMainApplicationClass();
}

这里ApplicationContextInitializer和ApplicationListener我们会在后面用到的时候说明它们的作用。
SpringApplication:

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();
    /* 加载工厂名称,Set防止重复 */
    Set<String> names = new LinkedHashSet<>(
            SpringFactoriesLoader.loadFactoryNames(type, classLoader));
    // 创建工厂实例
    List<T> instances = createSpringFactoriesInstances(type, parameterTypes,
            classLoader, args, names);
    // 根据@Order和@Priority进行排序
    AnnotationAwareOrderComparator.sort(instances);
    return instances;
}

SpringFactoriesLoader:

public static List<String> loadFactoryNames(Class<?> factoryClass, @Nullable ClassLoader classLoader) {
    String factoryClassName = factoryClass.getName();
    /* 加载工厂配置,根据传入的factoryClass获取工厂名称集合 */
    return loadSpringFactories(classLoader).getOrDefault(factoryClassName, Collections.emptyList());
}

SpringFactoriesLoader:

private static Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader) {
    MultiValueMap<String, String> result = cache.get(classLoader);
    if (result != null) {
        return result;
    }
    try {
        // 加载资源,路径META-INF/spring.factories
        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()) {
                // value用逗号分隔组成集合
                List<String> factoryClassNames = Arrays.asList(
                        StringUtils.commaDelimitedListToStringArray((String) entry.getValue()));
                // 添加key和集合的映射
                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文件中有什么内容:

# PropertySource Loaders
org.springframework.boot.env.PropertySourceLoader=\
org.springframework.boot.env.PropertiesPropertySourceLoader,\
org.springframework.boot.env.YamlPropertySourceLoader

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

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

# Application Context Initializers
org.springframework.context.ApplicationContextInitializer=\
org.springframework.boot.context.ConfigurationWarningsApplicationContextInitializer,\
org.springframework.boot.context.ContextIdApplicationContextInitializer,\
org.springframework.boot.context.config.DelegatingApplicationContextInitializer,\
org.springframework.boot.web.context.ServerPortInfoApplicationContextInitializer

# Application Listeners
org.springframework.context.ApplicationListener=\
org.springframework.boot.ClearCachesApplicationListener,\
org.springframework.boot.builder.ParentContextCloserApplicationListener,\
org.springframework.boot.context.FileEncodingApplicationListener,\
org.springframework.boot.context.config.AnsiOutputApplicationListener,\
org.springframework.boot.context.config.ConfigFileApplicationListener,\
org.springframework.boot.context.config.DelegatingApplicationListener,\
org.springframework.boot.context.logging.ClasspathLoggingApplicationListener,\
org.springframework.boot.context.logging.LoggingApplicationListener,\
org.springframework.boot.liquibase.LiquibaseServiceLocatorApplicationListener

# Environment Post Processors
org.springframework.boot.env.EnvironmentPostProcessor=\
org.springframework.boot.cloud.CloudFoundryVcapEnvironmentPostProcessor,\
org.springframework.boot.env.SpringApplicationJsonEnvironmentPostProcessor,\
org.springframework.boot.env.SystemEnvironmentPropertySourceEnvironmentPostProcessor

# Failure Analyzers
org.springframework.boot.diagnostics.FailureAnalyzer=\
org.springframework.boot.diagnostics.analyzer.BeanCurrentlyInCreationFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.BeanNotOfRequiredTypeFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.BindFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.BindValidationFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.UnboundConfigurationPropertyFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.ConnectorStartFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.NoUniqueBeanDefinitionFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.PortInUseFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.ValidationExceptionFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.InvalidConfigurationPropertyNameFailureAnalyzer,\
org.springframework.boot.diagnostics.analyzer.InvalidConfigurationPropertyValueFailureAnalyzer

# FailureAnalysisReporters
org.springframework.boot.diagnostics.FailureAnalysisReporter=\
org.springframework.boot.diagnostics.LoggingFailureAnalysisReporter

文件中我们看到了ApplicationContextInitializer和ApplicationListener的key value配置,还有一些其他的接口,遇到后我们在进行分析。构建好SpringApplication后,接下来就是运行它的run方法:
SpringApplication:

public ConfigurableApplicationContext run(String... args) {
    // StopWatch是一个简单的秒表,允许多个任务的计时,暴露每个命名任务的总运行时间和运行时间
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    ConfigurableApplicationContext context = null;
    Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
    configureHeadlessProperty();
    // 获取SpringApplicationRunListener集合,同样是从上面加载的配置中获取
    SpringApplicationRunListeners listeners = getRunListeners(args);
    listeners.starting();
    try {
        ApplicationArguments applicationArguments = new DefaultApplicationArguments(
                args);
        /* 准备环境 */
        ConfigurableEnvironment environment = prepareEnvironment(listeners,
                applicationArguments);
        configureIgnoreBeanInfo(environment);
        // 打印banner,就是我们在控制台看到的那个Spring的logo
        Banner printedBanner = printBanner(environment);
        // 根据不同的webApplicationType返回不同的应用上下文实例
        context = createApplicationContext();
        // 同样从上面加载的配置中获取SpringBootExceptionReporter
        exceptionReporters = getSpringFactoriesInstances(
                SpringBootExceptionReporter.class,
                new Class[] { ConfigurableApplicationContext.class }, context);
        /* 准备上下文 */
        prepareContext(context, environment, listeners, applicationArguments,
                printedBanner);
        /* 刷新上下文 */
        refreshContext(context);
        // 刷新后操作,默认空实现,子类覆盖
        afterRefresh(context, applicationArguments);
        stopWatch.stop();
        if (this.logStartupInfo) {
            new StartupInfoLogger(this.mainApplicationClass)
                    .logStarted(getApplicationLog(), stopWatch);
        }
        listeners.started(context);
        // 调用所有ApplicationRunner和CommandLineRunner的run方法
        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;
}

在这里我们看到很多处SpringApplicationRunListener的相关方法调用,我们来说明一下它的作用,就像它的命名一样,主要是监听SpringApplication的run方法的各个关键步骤,在上面加载的配置中,我们看到了一个实现为EventPublishingRunListener,主要作用是发布应用的启动运行、启动完成等一些关键事件,具体代码有兴趣的同学可以自行查阅。
SpringApplication:

private ConfigurableEnvironment prepareEnvironment(
        SpringApplicationRunListeners listeners,
        ApplicationArguments applicationArguments) {
    // 创建Environment
    ConfigurableEnvironment environment = getOrCreateEnvironment();
    /* 配置environment */
    configureEnvironment(environment, applicationArguments.getSourceArgs());
    listeners.environmentPrepared(environment);
    // 将environment绑定到SpringApplication
    bindToSpringApplication(environment);
    if (this.webApplicationType == WebApplicationType.NONE) {
        environment = new EnvironmentConverter(getClassLoader())
                .convertToStandardEnvironmentIfNecessary(environment);
    }
    // 附加一个ConfigurationPropertySource到environment
    ConfigurationPropertySources.attach(environment);
    return environment;
}

SpringApplication:

protected void configureEnvironment(ConfigurableEnvironment environment,
        String[] args) {
    // 在此应用程序的环境中添加、删除或重新排序PropertySource
    configurePropertySources(environment, args);
    // 配置此应用程序环境的激活(或默认为激活)配置文件
    // 可以通过spring.profiles.active属性在配置文件处理期间激活其他配置文件
    configureProfiles(environment, args);
}

SpringApplication:

private void prepareContext(ConfigurableApplicationContext context,
        ConfigurableEnvironment environment, SpringApplicationRunListeners listeners,
        ApplicationArguments applicationArguments, Banner printedBanner) {
    context.setEnvironment(environment);
    // 应用相应的ApplicationContext后置处理,子类可以覆盖,
    // 默认实现为context设置beanNameGenerator和resourceLoader
    postProcessApplicationContext(context);
    // 在context刷新之前应用之前加载的ApplicationContextInitializer
    // 在META-INF/spring.factories中默认配置了4个ApplicationContextInitializer,具体作用可以自行了解一下
    applyInitializers(context);
    listeners.contextPrepared(context);
    // 日志打印
    if (this.logStartupInfo) {
        logStartupInfo(context.getParent() == null);
        logStartupProfileInfo(context);
    }
    // 添加特定的boot单例bean
    context.getBeanFactory().registerSingleton("springApplicationArguments",
            applicationArguments);
    if (printedBanner != null) {
        context.getBeanFactory().registerSingleton("springBootBanner", printedBanner);
    }
    // 获取所有资源,示例中就是获取到我们的启动类
    Set<Object> sources = getAllSources();
    Assert.notEmpty(sources, "Sources must not be empty");
    // 加载资源注册成为Spring的bean
    load(context, sources.toArray(new Object[0]));
    listeners.contextLoaded(context);
}

SpringApplication:

private void refreshContext(ConfigurableApplicationContext context) {
    refresh(context);
    if (this.registerShutdownHook) {
        try {
            context.registerShutdownHook();
        }
        catch (AccessControlException ex) {
        }
    }
}

这里上下文的刷新和注册关闭钩子我们都在之前的Spring源码分析文章中分析过,不再赘述。读者可能会有疑惑,Spring boot不是有非常厉害的自动配置么,文章中并没有看到啊,Spring boot的自动配置我们会用单独的文章来分析,本篇文章我们主要分析整个启动流程的步骤和一些扩展,到这里,整个Spring boot的启动流程就分析完了。

    原文作者:Spring Boot
    原文地址: https://blog.csdn.net/heroqiang/article/details/83578685
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞