走进Spring Boot之第三步SpringApplication run方法

Spring BootJava大约 2457 字

代码走读

public ConfigurableApplicationContext run(String... args) {
    //计算启动时间
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    ConfigurableApplicationContext context = null;
    //异常报告集合
    Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
    //无显示界面,本就是后台服务,无需界面
    configureHeadlessProperty();
    //获取所有监听器,其实就一个EventPublishingRunListener
    //可参见spring.factories文件中的SpringApplicationRunListener配置
    SpringApplicationRunListeners listeners = getRunListeners(args);
    //启动EventPublishingRunListener
    listeners.starting();
    try {
        //java -jar启动时指定的参数,此处未配置
        ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
        //准备运行环境,加载配置文件解析器,读取配置文件,组成需要的运行环境
        ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
        configureIgnoreBeanInfo(environment);
        //打印Banner
        Banner printedBanner = printBanner(environment);
        //创建上下文,AnnotationConfigServletWebServerApplicationContext
        context = createApplicationContext();
        //加载spring.factories中的SpringBootExceptionReporter配置项
        exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,
                new Class[] { ConfigurableApplicationContext.class }, context);
        //准备上下文,包括设置运行环境,预处理、初始化上下文
        prepareContext(context, environment, listeners, applicationArguments, printedBanner);
        //刷新上下文,bean类在此方法内初始化
        refreshContext(context);
        //空实现
        afterRefresh(context, applicationArguments);
        //停止启动计时,此时已打印出 Started DemoApplication in 633.677 seconds (JVM running for 636.143)
        stopWatch.stop();
        if (this.logStartupInfo) {
            new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
        }
        //开启所有监听器
        listeners.started(context);
        //是否有ApplicationRunner/CommandLineRunner,如果有也一起启动,此处没有
        callRunners(context, applicationArguments);
    }
    catch (Throwable ex) {
        handleRunFailure(context, ex, exceptionReporters, listeners);
        throw new IllegalStateException(ex);
    }

    try {
        //运行所有监听器,发布ApplicationReadyEvent事件
        listeners.running(context);
    }
    catch (Throwable ex) {
        handleRunFailure(context, ex, exceptionReporters, null);
        throw new IllegalStateException(ex);
    }
    return context;
}
阅读 224 · 发布于 2020-04-05

————        END        ————

扫描下方二维码关注公众号和小程序↓↓↓

昵称:
随便看看换一批