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 应用启动完成后执行的,可以用来执行必要的初始化任务。

相关推荐
字节源流29 分钟前
关于maven的依赖下不下来的问题
java·maven
pjx9871 小时前
服务间的“握手”:OpenFeign声明式调用与客户端负载均衡
java·运维·spring·负载均衡
prinrf('千寻)2 小时前
MyBatis-Plus 的 updateById 方法不更新 null 值属性的问题
java·开发语言·mybatis
老华带你飞2 小时前
实习记录小程序|基于SSM+Vue的实习记录小程序设计与实现(源码+数据库+文档)
java·数据库·spring boot·小程序·论文·毕设·实习记录小程序
在未来等你2 小时前
互联网大厂Java求职面试:AI与大模型应用集成及云原生挑战
java·微服务·ai·kubernetes·大模型·embedding·spring ai
my_styles2 小时前
docker-compose部署项目(springboot服务)以及基础环境(mysql、redis等)ruoyi-ry
spring boot·redis·后端·mysql·spring cloud·docker·容器
源码技术栈2 小时前
SaaS基于云计算、大数据的Java云HIS平台信息化系统源码
java·大数据·云计算·云his·his系统·云医院·区域his
编程、小哥哥2 小时前
互联网大厂Java面试:从Spring Boot到微服务架构的技术深挖
java·spring boot·redis·微服务·prometheus·面试技巧
揽你·入怀3 小时前
数据结构:ArrayList简单实现与常见操作实例详解
java·开发语言
okok__TXF3 小时前
SpringBoot3+AI
java·人工智能·spring