CommandLineRunner、ApplicationRunner作用及区别

前言

        本文目的是探究CommandLineRunner、ApplicationRunner接口(以下简称Runner接口)作用、区别以及使用场景。

作用

        Runner接口由SpringBoot提供,在SpringApplication.run()方法中调用,因此通过实现Runner接口自定义初始化任务

Runner接口实现类调用位置

        

应用场景

         在我们实际工作中,总会遇到这样需求,在项目启动的时候需要做一些初始化的操作,比如初始化线程池,提前加载好加密证书等。可以通过实现Runner接口完成以上工作。

区别

        下图中两个接口都只有run()抽象方法,区别在于参数不同,CommandLineRunner中run()参数是数量可变的字符串,CommandLineRunner中run()参数是ApplicationArguments对象,那么这两种参数有什么区别?

CommandLineRunner、ApplicationArguments区别

   

        我们实现了这两个接口,并在启动程序时传入两种参数“--参数1=1 参数2 参数3”,对比两个接口对参数的不同处理

 CommandLineRunner实现

@Component
public class MyCommandLineRunner implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println("------------开始调用CommandLineRunner------------");
        for (String arg:args){
            System.out.println("  "+arg);
        }
        System.out.println("++++++++++++结束调用CommandLineRunner++++++++++++");
    }
}

日志输出

ApplicationRunner实现

@Component
public class MyApplicationRunner implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("------------开始调用ApplicationRunner------------");
        String[] sourceArgs = args.getSourceArgs();
        for (String arg:sourceArgs){
            System.out.println("  "+arg);
        }
        System.out.println("  -----------------option----------------    ");
        Set<String> optionNames = args.getOptionNames();
        for (String s: optionNames) {
            System.out.println("  optionName:"+s+"  optionValue:"+args.getOptionValues(s));
        }

        System.out.println("++++++++++++结束调用ApplicationRunner++++++++++++");
    }
}

日志输出

 

 结论

通过日志可以看出最大区别是ApplicationArgument会将“--option=value”格式的参数解析,并通过optionName获取value值。

补充

执行顺序

通过在实现类上添加@order()标签决定接口的的调用顺序

        

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值