23.8. 使用ApplicationRunner或CommandLineRunner
如果需要在SpringApplication启动后执行一些特殊的代码,你可以实现ApplicationRunner或CommandLineRunner接口,这两个接口工作方式相同,都只提供单一的run方法,该方法仅在SpringApplication.run(…)完成之前调用。
CommandLineRunner接口能够访问string数组类型的应用参数,而ApplicationRunner使用的是上面描述过的ApplicationArguments接口:
import org.springframework.boot.*import org.springframework.stereotype.*@Componentpublic class MyBean implements CommandLineRunner {public void run(String... args) {// Do something...}}
如果某些定义的CommandLineRunner或ApplicationRunner beans需要以特定的顺序调用,你可以实现org.springframework.core.Ordered接口或使用org.springframework.core.annotation.Order注解。
