如果在SpringApplication启动后需要运行某些特定代码,则可以实现ApplicationRunner 或 CommandLineRunner接口。 两个接口以相同的方式工作,并提供单个run方法,该方法在SpringApplication.run(…)完成之前调用。
CommandLineRunner接口提供对应用程序参数的访问,作为简单的字符串数组,而ApplicationRunner使用前面讨论的ApplicationArguments接口。 以下示例显示了带有run 方法的CommandLineRunner :
import org.springframework.boot.*;import org.springframework.stereotype.*;
@Component
public class MyBean implements CommandLineRunner {
public void run(String... args) {
// Do something...
}
}
如果定义了必须以特定顺序调用的多个CommandLineRunner or ApplicationRunner beans,则还可以实现org.springframework.core.Ordered接口或使用org.springframework.core.annotation.Order注解,如下代码所示:
import org.springframework.boot.*;import org.springframework.stereotype.*;
@Component
@Order(value = 0)
public class MyBean implements CommandLineRunner {
public void run(String... args) {
// Do something...
}
}
@Component
@Order(value = 1)
public class MyBean2 implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
// Do something ...
}
}
注:@Order 的值越小优先级越高。

本文介绍如何在SpringBoot应用启动后执行特定任务,通过实现CommandLineRunner或ApplicationRunner接口。文章详细解释了这两个接口的区别,前者提供对命令行参数的访问,后者使用ApplicationArguments接口。此外,还展示了如何通过实现Ordered接口或使用@Order注解来定义多个任务的执行顺序。
2万+

被折叠的 条评论
为什么被折叠?



