springboot启动流程简析

Spring Boot可以轻松创建独立的,生产级的基于Spring的应用程序,而这只需要很少的一些Spring配置。本文将从SpringBoot的启动流程角度简要的分析SpringBoot启动过程中主要做了哪些事情。

说明: springboot 2.0.6.RELEASE


SpringBoot启动简要流程图

SpringBoot启动流程

原始大图链接

启动流程概述

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

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 )

initializers将在ConfigurableApplicationContext的refresh方法之前调用,比如针对web应用来说,需要在refresh之前注册属性源或者激活指定的配置文件。

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

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


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进行响应。

  • 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启动过程中的各个阶段时发挥了什么作用?

猜你喜欢

转载自www.cnblogs.com/gsonkeno/p/10121652.html