使用ApplicationRunner或CommandLineRunner
如果启动后需要运行一些特定的代码SpringApplication,则可以实现ApplicationRunner或CommandLineRunner接口。这两个接口以相同的方式工作,并提供一个单一的run方法,该方法在SpringApplication.run(…)完成之前就被调用。
非常适合应在应用程序启动后但开始接受流量之前运行的任务。
所述CommandLineRunner接口提供访问的应用程序的参数作为一个字符串数组,而ApplicationRunner用途ApplicationArguments接口前面讨论。以下示例显示了一个CommandLineRunnerwithrun方法:
import org.springframework.boot.*;import org.springframework.stereotype.*;@Componentpublic class MyBean implements CommandLineRunner {public void run(String... args) {// Do something...}}
如果几个CommandLineRunner或ApplicationRunner豆类中定义必须在一个特定的顺序被调用,您还可以实现org.springframework.core.Ordered接口或使用org.springframework.core.annotation.Order注解。
