spring-boot启动

辉辉、 / 2024-08-12 / 原文

public ConfigurableApplicationContext run(String... args) {
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    //创建引导上下文
    DefaultBootstrapContext bootstrapContext = createBootstrapContext();
    ConfigurableApplicationContext context = null;
    configureHeadlessProperty();
    
    //生成启动监视器
    SpringApplicationRunListeners listeners = getRunListeners(args);
    
    //resources下创建META-INF/spring.factories文件
    //加载监听器如下方
    //org.springframework.boot.SpringApplicationRunListener=\
    //org.springframework.boot.context.event.EventPublishingRunListener
    listeners.starting(bootstrapContext, this.mainApplicationClass);
    try {
       //初始化应用参数类
       ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
        
       //准备环境参数
       ConfigurableEnvironment environment = prepareEnvironment(listeners, bootstrapContext, applicationArguments);
       configureIgnoreBeanInfo(environment);
        
       //打印图像控制台
       Banner printedBanner = printBanner(environment);
        
       //创建spring上下文
       context = createApplicationContext();
       context.setApplicationStartup(this.applicationStartup);
        
       //准备上下文
       //完成事件ApplicationContextInitializedEvent
       //完成事件ApplicationPreparedEvent
       prepareContext(bootstrapContext, context, environment, listeners, applicationArguments, printedBanner);
        
       //刷新上下文
       //上下文刷新完成事件ContextRefreshedEvent
       //Web服务器完成事件WebServerlnitializedEvent
       refreshContext(context);
        
       afterRefresh(context, applicationArguments);
       stopWatch.stop();
       if (this.logStartupInfo) {
          new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
       }
       listeners.started(context);
       callRunners(context, applicationArguments);
    }
    catch (Throwable ex) {
       handleRunFailure(context, ex, listeners);
       throw new IllegalStateException(ex);
    }

    try {
       listeners.running(context);
    }
    catch (Throwable ex) {
       handleRunFailure(context, ex, null);
       throw new IllegalStateException(ex);
    }
    return context;
}