转载请注明出处:
以下是 Spring boot中 CommandLineRunner 的定义:
package org.springframework.boot;
@FunctionalInterface
public interface CommandLineRunner {
void run(String... args) throws Exception;
}
CommandLineRunner 是 Spring Boot 提供的一个重要接口,用于在应用程序启动完成后执行特定逻辑。
关键特性:
- @FunctionalInterface:标记为函数式接口,支持 Lambda 表达式
- run(String... args):核心方法,在Spring Boot应用启动完成后执行
- args参数:接收命令行参数
- throws Exception:允许抛出异常
使用场景
- 应用启动后初始化数据
- 执行一次性任务
- 启动后台服务
- 验证配置信息
1. 基础实现方式
@Component
public class StartupRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("Application started with command-line arguments: " + Arrays.toString(args));
// 处理命令行参数
for (int i = 0; i < args.length; ++i) {
System.out.println("arg[" + i + "]: " + args[i]);
}
}
}
2. 多个CommandLineRunner执行顺序
@Component
@Order(1)
public class FirstRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("First runner executed");
}
}
@Component
@Order(2)
public class SecondRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("Second runner executed");
}
}
3.执行时机
CommandLineRunner 的 run() 方法在以下阶段执行:
- Spring Boot应用完全启动
- SpringApplication.run() 方法完成
- Web服务器已启动并监听端口(如果是Web应用)
- 所有 @PostConstruct 方法执行完毕
- 在 ApplicationReadyEvent 发布之前