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中需要指定定时周期任务(如一直循环打印某些信息等), 需要在异步线程中执行, 否则项目的主线程会一直阻塞 , 无法启动成功

posted @   懒惰的小熊  阅读(227)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示