SpringBoot使用CommandLineRunner和ApplicationRunner执行初始化业务

业务场景

在业务场景中, 有些情况下需要我们一启动项目就执行一些操作. 例如数据配置的相关初始化, 通用缓存的数据构造等. SpringBoot为我们提供了CommandLineRunner和ApplicationRunner两个接口来实现这个功能.

接口说明

CommandLineRunner和ApplicationRunner两个接口除了参数不同, 其他基本相同, 可以根据实际需求选择使用. CommandLineRunner中的run方法参数为String..., ApplicationRunner中的run方法参数为ApplicationArguments.在同等顺序中, ApplicationRunner会比CommandLineRunner优先执行

使用方法

定义一个类实现该接口, 重写其中的run方法即可. 如果有多个实现类, 我们可以通过@Order注解来定义优先级(数字越低越先执行)

@Order(1)
@Component
public class MyCommandLineRunner1 implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        System.out.println("========== 初始任务MyCommandLineRunner1 ==========");
    }
}

@Order(2)
@Component
public class MyCommandLineRunner2 implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        System.out.println("========== 初始任务MyCommandLineRunner2 ==========");
//        throw new RuntimeException("模拟异常");
    }
}

@Order(2)
@Component
public class MyApplicationRunner1 implements ApplicationRunner {

    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("========== 初始任务MyApplicationRunner1 ==========");
    }
}

启动项目, 输出如下:

注意事项:

1. CommandLineRunner和ApplicationRunner的执行其实是整个项目启动周期中的一部分, Runner执行完成后, 才最终启动项目.

2. 如果Runner中出现异常, 就会影响项目的启动, 所以要在Runner中处理异常

3. 如果Runner中需要指定定时周期任务(如一直循环打印某些信息等), 需要在异步线程中执行, 否则项目的主线程会一直阻塞 , 无法启动成功

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值