开发者社区> 问答> 正文

Spring Boot的启动流程是什么?

Spring Boot的启动流程是什么?

展开
收起
gxx1 2022-04-01 07:49:33 660 0
1 条回答
写回答
取消 提交回答
  • Spring Boot应用的整个启动流程都封装在SpringApplication.run方法中,本质上就是在spring的基础之上做了封装,做了大量的扩张,代码如下。

    public ConfigurableApplicationContext run(String... args) {

    StopWatch stopWatch = new StopWatch();

    stopWatch.start();

    context = null;

    Collection

    exceptionReporters = new ArrayList<>();

    configureHeadlessProperty();

    //1.通过SpringFactoriesLoader查找并加载所有的

    SpringApplicationRunListeners,通过调用

    //starting()方法通知所有的SpringApplicationRunListeners:应用 开始启动了

    SpringApplicationRunListeners listeners = getRunListeners(args);

    listeners.starting();

    try {

    //2.创建并配置当前应用将要使用的Environment

    ApplicationArguments applicationArguments = new

    DefaultApplicationArguments( args);

    ConfigurableEnvironment environment =

    prepareEnvironment(listeners,

    applicationArguments);

    configureIgnoreBeanInfo(environment);

    //3.打印banner

    Banner printedBanner = printBanner(environment);

    //4.根据是否是web项目,来创建不同的ApplicationContext容器

    context = createApplicationContext();

    //5.创建一系列FailureAnalyzer

    exceptionReporters = (

    .class,

    new Class[] { .class }, context);

    //6.初始化ApplicationContext

    prepareContext(context, environment, listeners, applicationArguments,

    printedBanner);

    //7.调用ApplicationContext的refresh()方法,刷新容器 refreshContext(context);

    //8.查找当前context中是否注册有CommandLineRunner和ApplicationRunner,如果有则遍历执行它们。

    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, listeners, exceptionReporters, ex);

    throw new IllegalStateException(ex);

    }

    listeners.running(context);

    return context;

    }

    上述代码就是启动流程,我们通过调用starting()方法通知所有的SpringApplicationRunListeners:。

    2022-04-01 07:53:43
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
云栖社区特邀专家徐雷Java Spring Boot开发实战系列课程(第20讲):经典面试题与阿里等名企内部招聘求职面试技巧 立即下载
微服务架构模式与原理Spring Cloud开发实战 立即下载
阿里特邀专家徐雷Java Spring Boot开发实战系列课程(第18讲):制作Java Docker镜像与推送到DockerHub和阿里云Docker仓库 立即下载