Spring Boot中 CommandLineRunner 与 ApplicationRunner作用、区别

CommandLineRunner 和 ApplicationRunner 是 Spring Boot 提供的两种用于在应用程序启动后执行初始化代码的机制。这两种接口允许你在 Spring 应用上下文完全启动后执行一些自定义的代码,通常用于执行一次性初始化任务,如数据库预填充、缓存预热等。

CommandLineRunner

CommandLineRunner 是一个简单的接口,它只有一个方法:

java 复制代码
public interface CommandLineRunner {
    void run(String... args) throws Exception;
}

此接口的 run 方法接受一个字符串数组参数,代表命令行参数。这意味着你可以访问应用启动时传递给它的参数。如果实现 CommandLineRunner 接口的类被 Spring 扫描到,那么它的 run 方法将在应用启动完成且所有单例 Bean 被创建之后执行。

ApplicationRunner

ApplicationRunner 类似于 CommandLineRunner,但它提供了更丰富的功能,特别是它允许你访问 ApplicationArguments 对象:

java 复制代码
public interface ApplicationRunner {
    void run(ApplicationArguments args) throws Exception;
}

ApplicationArguments 提供了对命令行参数的更高级访问,它能够区分选项和非选项参数,并能判断参数是否包含非选项参数。这对于需要处理复杂命令行参数的应用非常有用。

区别

主要的区别在于 ApplicationRunner 提供了对命令行参数的更精细控制,而 CommandLineRunner 则直接提供一个字符串数组。

执行顺序

如果存在多个 CommandLineRunner 或 ApplicationRunner 的实现,它们将按照 Bean 的定义顺序执行。如果需要自定义执行顺序,可以实现 Ordered 接口或使用 @Order 注解。

示例

这里是一个使用 CommandLineRunner 的示例:

java 复制代码
@Component
public class MyCommandLineRunner implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println("CommandLineRunner is running...");
    }
}

这里是一个使用 ApplicationRunner 的示例:

java 复制代码
@Component
public class MyApplicationRunner implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("ApplicationRunner is running...");
        if (args.containsOption("debug")) {
            System.out.println("Debug mode is enabled.");
        }
    }
}

示例执行结果

两者都是在 Spring Boot 应用启动完成后执行的,可以用来执行必要的初始化任务。

相关推荐
源代码•宸2 分钟前
Golang基础语法(go语言error、go语言defer、go语言异常捕获、依赖管理、Go Modules命令)
开发语言·数据库·后端·算法·golang·defer·recover
编程大师哥10 分钟前
Java 常见异常(按「运行时 / 编译时」分类)
java·开发语言
SnrtIevg13 分钟前
Vavr 用户指南
java·后端
PieroPC14 分钟前
用FastAPI 一个 后端 和 两个前端 原生HTML/CSS/JS 、Vue3 写一个博客系统 例
前端·后端
Way2top15 分钟前
Go语言动手写Web框架 - Gee第五天 中间件
后端·go
Way2top18 分钟前
Go语言动手写Web框架 - Gee第四天 分组控制
后端·go
喵叔哟19 分钟前
17.核心服务实现(上)
后端·.net
怦怦蓝24 分钟前
IDEA 开发邮件发送功能:全流程报错解决方案汇总
java·ide·intellij-idea·发邮件
艾莉丝努力练剑30 分钟前
【优选算法必刷100题:专题五】(位运算算法)第033~38题:判断字符是否唯一、丢失的数字、两整数之和、只出现一次的数字 II、消失的两个数字
java·大数据·运维·c++·人工智能·算法·位运算
大猫和小黄32 分钟前
Java开发过程中的各种ID生成策略
java·开发语言·id