Spring Boot源码-框架整体启动流程

Mars 2020年05月10日 37次浏览

Spring Boot源码-框架整体启动流程

框架初始化

  • 配置资源加载器
  • 配置primarySources
  • 应用环境检测
  • 配置系统初始化器
  • 配置应用监听器】
  • 配置main方法所在的类

框架启动

  • 计时器开始计时
  • Headless模式赋值
  • 发送ApplicationStartingEvent事件
  • 配置环境env模块
  • 发送ApplicationEnvironmentPrepareEvent事件
  • 打印banner
  • 创建应用上下文context对象
  • 初始化失败分析器
  • 关联spring boot组件与应用上下文对象
  • 发送ApplicationContextInitialzedEvent事件
  • 加载source到context
  • 发送ApplicationPrepareEvent事件
  • 刷新上下文(refresh)
  • 计时器停止计时
  • 发送ApplicationStartedEvent事件
  • 调用框架的启动扩展类(如,实现类ApplicationRunner接口)
  • 发送ApplicationReadyEvent事件

自动化装配流程

  • 收集配置文件中的配置工厂类
  • 加载组件工厂
  • 注册组件内自定义的bean

核心方法概览

public ConfigurableApplicationContext run(String... args) {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        ConfigurableApplicationContext context = null;
        Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList();
        this.configureHeadlessProperty();
        SpringApplicationRunListeners listeners = this.getRunListeners(args);
        listeners.starting();

        Collection exceptionReporters;
        try {
            ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
            ConfigurableEnvironment environment = this.prepareEnvironment(listeners, applicationArguments);
            this.configureIgnoreBeanInfo(environment);
            Banner printedBanner = this.printBanner(environment);
            context = this.createApplicationContext();
            exceptionReporters = this.getSpringFactoriesInstances(SpringBootExceptionReporter.class, new Class[]{ConfigurableApplicationContext.class}, context);
            this.prepareContext(context, environment, listeners, applicationArguments, printedBanner);
            this.refreshContext(context);
            this.afterRefresh(context, applicationArguments);
            stopWatch.stop();
            if (this.logStartupInfo) {
                (new StartupInfoLogger(this.mainApplicationClass)).logStarted(this.getApplicationLog(), stopWatch);
            }

            listeners.started(context);
            this.callRunners(context, applicationArguments);
        } catch (Throwable var10) {
            this.handleRunFailure(context, var10, exceptionReporters, listeners);
            throw new IllegalStateException(var10);
        }

        try {
            listeners.running(context);
            return context;
        } catch (Throwable var9) {
            this.handleRunFailure(context, var9, exceptionReporters, (SpringApplicationRunListeners)null);
            throw new IllegalStateException(var9);
        }
    }

该方法内的每一个方法调用都应该熟悉

启动流程图

Spring Boot启动流程.jpg