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); } } }
  • 相关阅读:
    九度OJ 1031:xxx定律 (基础题)
    九度OJ 1030:毕业bg (01背包、DP)
    九度OJ 1029:魔咒词典 (排序)
    九度OJ 1028:继续畅通工程 (最小生成树)
    九度OJ 1027:欧拉回路 (欧拉回路)
    九度OJ 1026:又一版 A+B (进制转换)
    九度OJ 1025:最大报销额 (01背包、DP)
    九度OJ 1024:畅通工程 (最小生成树)
    九度OJ 1023:EXCEL排序 (排序)
    九度OJ 1022:游船出租 (统计)
  • 原文地址:https://www.cnblogs.com/dk1024/p/15648870.html
Copyright © 2011-2022 走看看