23.8. 使用ApplicationRunner或CommandLineRunner

如果需要在SpringApplication启动后执行一些特殊的代码,你可以实现ApplicationRunnerCommandLineRunner接口,这两个接口工作方式相同,都只提供单一的run方法,该方法仅在SpringApplication.run(…)完成之前调用。

CommandLineRunner接口能够访问string数组类型的应用参数,而ApplicationRunner使用的是上面描述过的ApplicationArguments接口:

  1. import org.springframework.boot.*
  2. import org.springframework.stereotype.*
  3. @Component
  4. public class MyBean implements CommandLineRunner {
  5. public void run(String... args) {
  6. // Do something...
  7. }
  8. }

如果某些定义的CommandLineRunnerApplicationRunner beans需要以特定的顺序调用,你可以实现org.springframework.core.Ordered接口或使用org.springframework.core.annotation.Order注解。