• 剖析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); } } }
  • 相关阅读:
    我的安全测试面试_自问自答,不亦乐乎
    Linux Shell 网络层监控脚本(监控包括:连接数、句柄数及根据监控反馈结果分析)
    netstat监控大量ESTABLISHED连接与Time_Wait连接问题
    详解 Spotlight on MySQL监控MySQL服务器
    详解 Spotlight on Unix 监控Linux服务器
    某听书网站系统漏洞,利用抓包拼接方式获取网站资源
    不懂得使用工具的测试不是好测试
    【好书摘要】性能优化中CPU、内存、磁盘IO、网络性能的依赖
    性能调优从哪里入手
    报文解析,从请求报文详细讲到响应码
  • 原文地址:https://www.cnblogs.com/dk1024/p/15648870.html
Copyright © 2020-2023  润新知