SpringBoot入門十一,啟動後自動執行指定代碼
阿新 • • 發佈:2018-11-16
自動 err pro code watermark 技術分享 cep not cache
Springboot設置啟動後自動執行指定代碼,可以調用這兩個接口:
ApplicationRunner
CommandLineRunner
他們的執行時機為容器啟動完成的時候,這裏使用ApplicationRunner來實現需要的效果,直接上代碼:
import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; @Component @Order(1) // 如果有多個類實現了ApplicationRunner接口,可以使用此註解指定執行順序 public class SysEhcacheInit implements ApplicationRunner { @Override public void run(ApplicationArguments args) throws Exception { System.out.println("SysEhcacheInit執行時啟動了~~"); } }
註意:代碼中的@Order代表執行優先級,越小優先級越高
效果如下:
SpringBoot入門十一,啟動後自動執行指定代碼