如果需要在SpringApplication启动后运行一些特定的代码,您可以实现ApplicationRunner或者CommandLineRunner接口。两个接口以相同的方式工作,并且提供了一个会在SpringApplication.run(…)完成之前被调用的run方法。
CommandLineRunner接口以一个简单的字符串数组来提供对程序参数的访问,而ApplicationRunner使用了上面讨论的ApplicationArguments接口。
import org.springframework.boot.*
import org.springframework.stereotype.*
@Component
public class MyBean implements CommandLineRunner {
public void run(String... args) {
// Do something...
}
}
您还可以实现org.springframework.core.Ordered接口或使用org.springframework.core.annotation.Order注解,如果定义了多个CommandLineRunner或ApplicationRunnerbean,它们必须按照指定的顺序被调用。