SpringBoot 启动后运行特定的代码

在SpringApplication启动后,可以通过实现ApplicationRunner或CommandLineRunner接口来执行自定义的初始化任务。这两个接口在应用开始接受流量前调用,CommandLineRunner能访问命令行参数,而ApplicationRunner使用ApplicationArguments接口。当同时存在多个实现时,可以通过Order注解指定执行顺序。Order值越小,执行越早。如果未指定Order,ApplicationRunner优先于CommandLineRunner。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. ApplicationRunner 或 CommandLineRunner

如果你需要在 SpringApplication 启动后运行一些特定的代码,你可以实现 ApplicationRunner 或 CommandLineRunner 接口。这两个接口的工作方式相同,并提供一个单一的运行方法,该方法在 SpringApplication.run(…) 完成之前被调用。

这种契约很适合那些应该在应用程序启动后但在其开始接受流量前运行的任务。

CommandLineRunner 接口提供了对作为字符串数组的应用程序参数的访问,而 ApplicationRunner 使用 ApplicationArguments 接口。下面的例子显示了一个带有运行方法的 CommandLineRunner。

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

// Order 注解的value值越小,越先被加载,value的取值范围和 Integer 取值范围相同
@Component
@Order(value=1)
public class MyCommandLineRunner implements CommandLineRunner {
    @Override
    public void run(String... args) {
        // Do something
    }
}

如果定义了几个 CommandLineRunner 或 ApplicationRunner Bean,它们必须以特定的顺序被调用,你可以另外实现 org.springframework.core.Ordered 接口或使用 org.springframework.core.annotation.Order注解。Order 注解的value值越小,越先被加载,value的取值范围和 Integer 取值范围相同

注意:
CommandLineRunner 或 ApplicationRunner 同时存在时 Order 注解的值相同或都没有指定Order值,则优先加载 ApplicationRunner 的代码逻辑,若 CommandLineRunner 的 Order 注解的值小于 ApplicationRunner 的 Order 的值则优先加载 CommandLineRunner 的代码逻辑。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值