23.8 Using the ApplicationRunner or CommandLineRunner
如果你需要在SpringApplication
启动时执行一些指定的代码,你能实现ApplicationRunner
或CommandLineRunner
接口。这两个接口工作方式相似并提供一个run
方法,这个方法在SpringApplication.run()
完成之前被调用。
CommandLineRunner
接口提供的run
方法使用字符串数组作为方法参数,ApplicationRunner
接口提供的run
方法使用ApplicationArguments
对象作为方法。
import org.springframework.boot.*
import org.springframework.stereotype.*
@Component
public class MyBean implements CommandLineRunner {
public void run(String... args) {
// Do something...
}
}
如果定义了多个CommandLineRunner
或ApplicationRunner
,且这些bean
需要按指定的顺序调用,你能采用额外实现org.springframework.core.Ordered
或使用org.springframework.core.annotation.Order
注解的方式来控制调用顺序。