自学内容网 自学内容网

SpringBoot启动流程之终篇

整体流程

SpringBoot启动过程:
springboot启动过程
我们基本讨论前18步骤,现在就还有三个步骤讲完。

   /**
     * 启动方法
     * @param args
     * @return
     */
    public ConfigurableApplicationContext run(String... args) {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        //....省略

        try {
          
            //派发已开始事件
            listeners.started(context);
            //回调run方法
            this.callRunners(context, applicationArguments);
            //......此处省略代码
           //派发运行中的事件
           listeners.running(context);
           //......此处省略代码
  
    }

派发已开始事件

 listeners.started(context);

这里的事件在上下文没有完成创建之前都是EventPublishingRunListener.initialMulticaster派发的事件,而完成上下文之后,都是采用context去发布事件了

  public void started(ConfigurableApplicationContext context) {
        context.publishEvent(new ApplicationStartedEvent(this.application, this.args, context));
        AvailabilityChangeEvent.publish(context, LivenessState.CORRECT);
  }

回调run方法

this.callRunners(context, applicationArguments);

在我们使用SpringBoot的时候,如果我们想SpringBoot启动之后执行一些逻辑,那我们可以实现两个接口分别是org.springframework.boot.ApplicationRunnerorg.springframework.boot.CommandLineRunner,然后重写他的run方法,在这个时候,就会回调所有实现这两个接口的bean的run方法。

    /**
     * 回调run方法
     * @param context 上下文容器
     * @param args 参数
     */
    private void callRunners(ApplicationContext context, ApplicationArguments args) {
        List<Object> runners = new ArrayList();
        runners.addAll(context.getBeansOfType(ApplicationRunner.class).values());
        runners.addAll(context.getBeansOfType(CommandLineRunner.class).values());
        AnnotationAwareOrderComparator.sort(runners);
        Iterator var4 = (new LinkedHashSet(runners)).iterator();

        while(var4.hasNext()) {
            Object runner = var4.next();
            if (runner instanceof ApplicationRunner) {
                this.callRunner((ApplicationRunner)runner, args);
            }

            if (runner instanceof CommandLineRunner) {
                this.callRunner((CommandLineRunner)runner, args);
            }
        }

    }

this.callRunner代码如下,主要是先执行ApplicationRunner的接口实例,在执行CommandLineRunner接口的实例

 private void callRunner(ApplicationRunner runner, ApplicationArguments args) {
        try {
            runner.run(args);
        } catch (Exception var4) {
            throw new IllegalStateException("Failed to execute ApplicationRunner", var4);
        }
    }   
 private void callRunner(CommandLineRunner runner, ApplicationArguments args) {
        try {
            runner.run(args.getSourceArgs());
        } catch (Exception var4) {
            throw new IllegalStateException("Failed to execute CommandLineRunner", var4);
        }
    }

派发运行中的事件

当我们回调玩run方法以后,在派发一个运行中的事件,事件最后也是委托给上下文容器处理,至此,SpringBoot大概流程讲完,88


原文地址:https://blog.csdn.net/weixin_45653328/article/details/142480677

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!