SpringBoot启动系统任务案例

SpringBoot提供了CommandLineRunner和ApplicationRunner来处理系统启动时的任务,如配置加载和数据库初始化。CommandLineRunner按照@Order注解的数字顺序执行,ApplicationRunner则能处理命令行参数,包括非选项参数和选项参数。
摘要由CSDN通过智能技术生成

  有一些特殊的任务需要在系统启动时执行,例如配置文件加载、数据库初始化等操作。SpringBoot对此提供了两种解决方案CommandLineRunner和ApplicationRunner。

方式一:CommandLineRunner

@Component
@Order(1)
public class CommandLineRunner1 implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println("CommandLineRunner1启动:"+Arrays.toString(args));
    }
}

@Component
@Order(2)
public class CommandLineRunner2 implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println("CommandLineRunner2启动:"+Arrays.toString(args));
    }
}

@Order数字越小越先执行,参数args就是系统启动时main带过来的参数

方式二:ApplicationRunner

@Component
@Order(3)
public class ApplicationRunner3 implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        List<String> nonOptionArgs = args.getNonOptionArgs();
        System.out.println("ApplicationRunner3启动:"+nonOptionArgs);
        Set<String> optionNames = args.getOptionNames();
        for (String optionName : optionNames) {
            System.out.println("key:"+optionName+",value:"+args.getOptionValues(optionName));
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值