如果在SpringApplication啟動後需要運作某些特定代碼,則可以實作ApplicationRunner 或 CommandLineRunner接口。 兩個接口以相同的方式工作,并提供單個run方法,該方法在SpringApplication.run(…)完成之前調用。
CommandLineRunner接口提供對應用程式參數的通路,作為簡單的字元串數組,而ApplicationRunner使用前面讨論的ApplicationArguments接口。 以下示例顯示了帶有run 方法的CommandLineRunner :
import org.springframework.boot.*;import org.springframework.stereotype.*;
@Component
public class MyBean implements CommandLineRunner {
public void run(String... args) {
// Do something...
}
}
如果定義了必須以特定順序調用的多個CommandLineRunner or ApplicationRunner beans,則還可以實作org.springframework.core.Ordered接口或使用org.springframework.core.annotation.Order注解,如下代碼所示:
import org.springframework.boot.*;import org.springframework.stereotype.*;
@Component
@Order(value = 0)
public class MyBean implements CommandLineRunner {
public void run(String... args) {
// Do something...
}
}
@Component
@Order(value = 1)
public class MyBean2 implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
// Do something ...
}
}
注:@Order 的值越小優先級越高。