zoukankan      html  css  js  c++  java
  • 剖析ApplicationRunner、CommandLineRunner

    需求:SpringBoot项目启动成功后执行某方法

    方案:在spring-boot中提供了两种Runner接口:ApplicationRunner和CommandLineRunner,编写自己的类实现这两种接口的run方法,均可实现需求

             不同的是实现的两个run方法接收的参数不同,这也是他俩唯一的不同,

              ApplicationRunner 接收的是 ApplicationArguments 类型的参数,即应用程序启动参数

              CommandLineRunner 接收的是String类型的可变参数,它的值就是我们main函数接收到的命令行参数(此参数可通过Run Configurations中的Arguments添加)

    Runner源码解析:SpringApplication.run 方法源代码执行成功的最后一步调用了 callRunners(context, applicationArguments),

                              此方法内部搜集了当前容器中所有的Runner类型的实体,并遍历调用其run方法,实现了后置的方法调用功能,具体源码如下

    ① SpringBoot主启动类:

        public static void main(String[] args) {
            SpringApplication springApplication = new SpringApplication(CcwebApplication.class);
            springApplication.run(args);
    
        }

    ②run方法最后一步

        public ConfigurableApplicationContext run(String... args) {
           ...
    
                listeners.started(context);
                // 寻找并调用当前容器中所有Runner
                this.callRunners(context, applicationArguments);
          ...
        }

    ③ 遍历执行所有Runner

        private void callRunners(ApplicationContext context, ApplicationArguments args) {
            List<Object> runners = new ArrayList();
    // 找到上下文中所有实现了ApplicationRunner的类 runners.addAll(context.getBeansOfType(ApplicationRunner.
    class).values());
    // 找到上下文中所有实现了CommandLineRunner的类 runners.addAll(context.getBeansOfType(CommandLineRunner.
    class).values());
    // 根据@Order注解的Value值进行排序 AnnotationAwareOrderComparator.sort(runners); Iterator var4
    = (new LinkedHashSet(runners)).iterator(); // 依次调用run 方法 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); } } }
  • 相关阅读:
    怎样跟老板提加薪,来看看自己值多少钱
    leetcode-204-Count Primes
    Atitit. 异常的使用总结最佳实践java .net php Vo8f
    设计模式——第一课
    linux svn命令具体解释
    BTrace介绍和生产环境样例
    5.3.5 namedtuple() 创建命名字段的元组结构
    linux驱动开发之九鼎板载蜂鸣器驱动测试【转】
    hrtimer高精度定时器的简单使用【学习笔记】
    Linux时间子系统之(一):时间的基本概念【转】
  • 原文地址:https://www.cnblogs.com/dk1024/p/15648870.html
Copyright © 2011-2022 走看看