Runner使用
Spring Boot Runner 详解:ApplicationRunner 与 CommandLineRunner 实战指南
在 Spring Boot 应用中,若需在 SpringApplication.run() 启动完成后自动执行初始化逻辑(如加载配置、初始化缓存、校验依赖服务),可通过 ApplicationRunner 或 CommandLineRunner 接口实现。这两个接口均为 Spring Boot 提供的 “启动后回调” 扩展点,核心作用是在 Spring 上下文初始化完成后、应用对外提供服务前执行自定义逻辑。从 “接口差异→实现方式→执行顺序→实战场景” 四个维度,系统讲解 Runner 的使用方法与底层原理。
Runner 接口核心作用与差异
ApplicationRunner 和 CommandLineRunner 功能高度相似,均用于 “启动后执行逻辑”,但在参数接收方式上存在关键差异,适用于不同场景。
1. 接口定义对比
(1)ApplicationRunner 接口
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
public interface ApplicationRunner {
// 参数为 ApplicationArguments 对象,支持解析命令行参数(含选项参数和非选项参数)
void run(ApplicationArguments args) throws Exception;
}
(2)CommandLineRunner 接口
import org.springframework.boot.CommandLineRunner;
public interface CommandLineRunner {
// 参数为 String 数组,直接接收原始命令行参数(不解析,按输入顺序存储)
void run(String... args) throws Exception;
}