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 的配置,还有一些其他的接口,遇到后再进行分析。构建好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) {
    // 刷新 Spring 上下文
    refresh(context);
    if (this.registerShutdownHook) {
        try {
            context.registerShutdownHook();
        }
        catch (AccessControlException ex) {
        }
    }
}

Spring上下文刷新的流程请参考https://blog.csdn.net/heroqiang/article/details/79010294
Spring boot 自动配置流程请参考https://blog.csdn.net/heroqiang/article/details/83794086
本篇文章主要分析整个启动流程的步骤和一些扩展,到这里,Spring boot 的启动流程就分析完了。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值