Spring boot 中 CommandLineRunner 在服务启动完成后自定义执行

转载请注明出处:

  以下是 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 发布之前
相关推荐
Flittly5 小时前
【AgentScope Java新手村系列】(16)从RAG到多路检索
java·spring boot·spring
小兔崽子去哪了5 小时前
Java 生成二维码解决方案
java·后端
人活一口气10 小时前
从JVM调优到MCP协议:Java全栈技术体系深度总结与企业级架构实践
java·spring boot
NE_STOP11 小时前
Vibe Coding -- 完整项目案例实操
java
荣码11 小时前
GraphRAG:普通RAG只能回答"点"的问题,我踩了4个坑才搞懂
java·python
SimonKing11 小时前
Google第三方授权登录
java·后端·程序员
明月光81811 小时前
从一行 @Builder 说起:重新拾起 Java 的 Lombok、注解与 Builder 模式
java
考虑考虑21 小时前
Mybatis实现批量插入
java·后端·mybatis
咖啡八杯21 小时前
GoF设计模式——中介者模式
java·后端·spring·设计模式
青石路1 天前
记一次多JDK版本问题的排查,一坑套一坑,差点没爬上来
java