在一些場景中,當SpringBoot項目啟動后,我們可能會需要做一些寫入緩存或者初始常量信息等的初始化工作,此時便需要使用SpringBoot提供的Runner來實現。
SpringBoot實際上給我們提供了兩種在應用啟動后立即執行某些方法的方式,它們分別是【ApplicationRunner】和【CommandLineRunner】。兩者的相同的在於它們都是在SpringApplication執行之后開始執行的,而不同點則在於CommandLineRunner接口提供的方法只能傳遞字符串,而ApplicationRunner是使用ApplicationArguments用來接收參數的,因此這個方式可以在更加復雜的場景中使用。
通過實現CommandLineRunner接口來實現啟動后執行特定邏輯
@Component public class InitRunner implements CommandLineRunner { /** * 在服務啟動完成(特指SpringApplication)后立即執行 */ @Override public void run(String... args) throws Exception { System.out.println("This will be executed when the project is started!"); } }
通過實現ApplicationRunner接口來實現啟動后執行特定邏輯
@Component public class InitRunner implements ApplicationRunner { /** * 在服務啟動完成(特指SpringApplication)后立即執行 */ @Override public void run(ApplicationArguments args) throws Exception { System.out.println("This will be executed when the project is started!"); } }
這兩種方式的實現都很簡單,直接實現了相應的接口就可以了,但別忘了要在類上加上@Component注解。
注冊多個實現並指定初始化工作的優先級
如果想要將多個初始化工作拆分開的話,只要生成多個實現類即可。
另外如果想要指定啟動方法執行的順序的話,則可以通過實現【org.springframework.core.Ordered】接口或者使用【org.springframework.core.annotation.Order】注解來實現目的。
@Component @Order(value = 1) public class InitRunner1 implements ApplicationRunner { @Override public void run(ApplicationArguments args) throws Exception { System.out.println("i like yanggb!"); } }
@Component @Order(value = 2) public class InitRunner2 implements ApplicationRunner { @Override public void run(ApplicationArguments args) throws Exception { System.out.println("i like yanggb too!"); } }
在@Order注解中指定的value值越小,則執行的優先級越高,比如在上面的代碼中就會先打印出【i like yanggb!】,然后再打印出【i like yanggb too!】。
"所有不合時宜的相遇都是遺憾。"