springboot启动流程简析

Spring Boot能够轻松建立独立的,生产级的基于Spring的应用程序,而这只须要不多的一些Spring配置。本文将从SpringBoot的启动流程角度简要的分析SpringBoot启动过程当中主要作了哪些事情。java

说明: springboot 2.0.6.RELEASEweb


SpringBoot启动简要流程图

SpringBoot启动流程

原始大图连接redis

启动流程概述

启动流程从角度来看,主要分两个步骤。第一个步骤是构造一个SpringApplication应用,第二个步骤是调用它的run方法,启动应用。spring

1 构造SpringApplication应用

public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
        //资源加载器默认为null
        this.resourceLoader = resourceLoader;
        Assert.notNull(primarySources, "PrimarySources must not be null");
        //primarySources这里指的是执行main方法的主类
        this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
        //根据classpath推断出应用类型,主要有NONE,SERVLET,REACTIVE三种类型
        this.webApplicationType = WebApplicationType.deduceFromClasspath();
        //经过SpringFactoriesLoader工具类获取META-INF/spring.factories中配置的一系列
        //ApplicationContextInitializer接口的子实现类
        setInitializers((Collection) getSpringFactoriesInstances(
                ApplicationContextInitializer.class));
        //基本同上,也是经过SpringFactoriesLoader工具类获取配置的ApplicationListener
        //接口的子实现类
        setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
        //经过方法调用堆栈获取到main执行方法的主类
        this.mainApplicationClass = deduceMainApplicationClass();
    }

SpringApplication的构造函数中为SpringApplication作了一些初始化配置,包括
主资源类(通常是启动类 primarySources )、
应用类型(webApplicationType )、
应用环境上下文初始化器(initializers)、
应用监听器(listeners)、
main方法主类(mainApplicationClass )springboot

initializers将在ConfigurableApplicationContext的refresh方法以前调用,好比针对web应用来讲,须要在refresh以前注册属性源或者激活指定的配置文件。app

listeners将在AbstractApplicationContext的refresh()方法中,先被注册到IOC容器中,IOC容器中剩下的非懒加载的单例被实例化后,IOC容器发布相应的事件,这些事件最终会调用与之相关联的AplicationListener的onApplicationEvent方法less

可对照文章顶部的流程图和源码分析函数


2 运行SpringApplication运行

/**建立并刷新应用上下文**/
    public ConfigurableApplicationContext run(String... args) {
        //spring-core包下的计时器类,在这里主要用来记录应用启动的耗时
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        ConfigurableApplicationContext context = null;
        Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
        
        //系统配置设置为headless模式
        configureHeadlessProperty();
        //经过SpringFactoriesLoader工具类获取META-INF/spring.factories
        //文件中SpringApplicationRunListeners接口的实现类,在这里是
        //EventPublishingRunListener
        SpringApplicationRunListeners listeners = getRunListeners(args);
        
        //广播ApplicationStartingEvent事件使应用中的ApplicationListener
        //响应该事件
        listeners.starting();
        try {
            ApplicationArguments applicationArguments = new DefaultApplicationArguments(
                    args);
            //准备应用环境,这里会发布ApplicationEnvironmentPreparedEvent事件
            //并将environment绑定到SpringApplication中
            ConfigurableEnvironment environment = prepareEnvironment(listeners,
                    applicationArguments);
            
            configureIgnoreBeanInfo(environment);
            //打印彩蛋
            Banner printedBanner = printBanner(environment);
            //根据成员变量webApplicationType建立应用上下文
            context = createApplicationContext();
            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);
            }
            //广播ApplicationStartedEvent事件使应用中的ApplicationListener
            //响应该事件
            listeners.started(context);
            
            //应用上下文中的ApplicationRunner,CommandLineRunner执行run方法
            callRunners(context, applicationArguments);
        }
        catch (Throwable ex) {
            handleRunFailure(context, ex, exceptionReporters, listeners);
            throw new IllegalStateException(ex);
        }

        try {
            //广播ApplicationReadyEvent事件使应用中的ApplicationListener
            //响应该事件     
            listeners.running(context);
        }
        catch (Throwable ex) {
            handleRunFailure(context, ex, exceptionReporters, null);
            throw new IllegalStateException(ex);
        }
        //返回应用上下文
        return context;
    }
  • 在启动过程当中,SpringApplicationListener在不一样阶段经过调用自身的不一样方法(如starting()、environmentPrepared())发布相应事件,通知ApplicationListener进行响应。spring-boot

  • refreshContext(context)方法是构建IOC容器最复杂的一步,绝大多数bean的定义加载以及实例化都在这一步执行。包括但不限于BeanFactoryPostProcessor、BeanPostProcessor、ApplicationEventMulticaster、@Controller,@Component等注解的组件。工具

  • SpringFactoriesLoader工具类,在SpringApplication的构造过程当中、运行过程当中都起到了极其重要的做用。SpringBoot的自动化配置功能一个核心依赖点就在该类上,该类经过读取类路径下的META-INF/spring.factories文件获取各类各样的工厂接口的实现类,经过反射获取这些类的类对象、构造方法,最终生成实例。

总结

  1. SpringApplication的构造过程当中,配置了SpringApplication应用上下文的一些基本元素,如应用类型webApplicationType、应用初始化器ApplicationContextInitializer、应用监听器ApplicationListener等。这些元素在SpringApplication的执行run()过程当中,都会在不一样阶段发挥不一样的做用
  2. SpringApplication的执行run()过程当中,一方面要初始化IOC容器(主要是bean的加载与初始化),一方面要在不一样的阶段直接或间接回调ApplicationListener或ApplicationRunner等其余接口的方法
  3. SpringFactoriesLoader是SpringBoot自动化配置功能极其关键的一环,它读取类路径下META-INF/spring.factories文件中工厂接口的实现类,来获取各类各类的Bean工厂实例,最终获取到自动化配置的bean。

备注:下一篇将经过spring-boot-starter-data-redis来分析SpringBoot对redis的自动化配置是如何操做的,以及SpringFactoriesLoader在SpringApplication启动过程当中的各个阶段时发挥了什么做用?

相关文章
相关标签/搜索