如果在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 的值越小优先级越高。