SpringBoot启动流程简要分析

在这里插入图片描述
SpringBoot作为Java开发者必备的框架,通过SpringBoot我们可以快速创建一个准生产级别的项目,极大的提升了开发效率,所以通过阅读SpringBoot的源代码,我们可以更好的了解SpringBoot的原理。
我们可以通过SpringBoot项目的启动类中找到run方法,查看最后的run方法的源码可以得出大致的启动流程。
在run方法中SpringBoot主要做了:

  • 获取监听器和属性参数配置
  • 打印 Banner 图标
  • 创建并初始化容器
  • 监听发送通知

除了这些,从源码中可以看出,run方法还包括启动时间的统计,异常报告,启动日志等操作。

public ConfigurableApplicationContext run(String... args) {
    
    
    // 记录启动开始时间
    long startTime = System.nanoTime();
    DefaultBootstrapContext bootstrapContext = this.createBootstrapContext();
    ConfigurableApplicationContext context = null;
    this.configureHeadlessProperty();
    // 获取 SpringApplicationRunListener 监听器
    SpringApplicationRunListeners listeners = this.getRunListeners(args);
    // 启动获得的所有监听器
    listeners.starting(bootstrapContext, this.mainApplicationClass);

    try {
    
    
        // 创建 ApplicationArguments 对象
        ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
        // 初始化加载属性配置,包括所有的配置属性
        ConfigurableEnvironment environment = this.prepareEnvironment(listeners, bootstrapContext, applicationArguments);
        this.configureIgnoreBeanInfo(environment);
        // 打印 Banner 图标
        Banner printedBanner = this.printBanner(environment);
        // 创建容器 ConfigurableApplicationContext
        context = this.createApplicationContext();
        context.setApplicationStartup(this.applicationStartup);
        // 准备容器
        this.prepareContext(bootstrapContext, context, environment, listeners, applicationArguments, printedBanner);
        // 初始化容器
        this.refreshContext(context);
        this.afterRefresh(context, applicationArguments);
        // 统计启动时间
        Duration timeTakenToStartup = Duration.ofNanos(System.nanoTime() - startTime);
        if (this.logStartupInfo) {
    
    
            (new StartupInfoLogger(this.mainApplicationClass)).logStarted(this.getApplicationLog(), timeTakenToStartup);
        }
        // 监听器发出通知,容器完成启动
        listeners.started(context, timeTakenToStartup);
        this.callRunners(context, applicationArguments);
    } catch (Throwable var12) {
    
    
        this.handleRunFailure(context, var12, listeners);
        throw new IllegalStateException(var12);
    }

    try {
    
    
        Duration timeTakenToReady = Duration.ofNanos(System.nanoTime() - startTime);
        // 监听器通知容器开始运行
        listeners.ready(context, timeTakenToReady);
        return context;
    } catch (Throwable var11) {
    
    
        this.handleRunFailure(context, var11, (SpringApplicationRunListeners)null);
        throw new IllegalStateException(var11);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_45523411/article/details/126957654