hello,你們好,我是小黑,又和你們見面啦~~java
若是你去某度搜索關鍵詞 CommandLineRunner 初始化資源
,截止小黑同窗寫這篇推文以前,大概能收到 1,030,000
個結果。app
網上大部分的文章都在告訴咱們說可使用 CommandLineRunner
去初始化資源,但幾乎不多有文章告訴咱們:若是 CommandLineRunner
使用不當,就會致使程序出現一些奇怪的異常,更有可能致使咱們的應用直接中止運行。ide
正在讀這篇文章的你若是也使用了 CommandLineRunner
去初始化資源,那麼小黑同窗勸你耗子尾汁,趕忙來看一下下面這些案例吧~測試
@Slf4j @SpringBootApplication public class CommandLineRunnerDemoApp { private Map<String, String> map; public static void main(String[] args) { SpringApplication.run(CommandLineRunnerDemoApp.class, args); } @RestController public class controller { @GetMapping("/name") public String name() { return map.get("name"); } } @Bean public CommandLineRunner commandLineRunner() { return args -> { // 模擬加載數據過慢 log.info("start do commandLineRunner..."); TimeUnit.MINUTES.sleep(1); map = ImmutableMap.of("namne", "coder小黑"); log.info("do commandLineRunner end"); }; } }
Spring 容器啓動以後,訪問 http://localhost:8080/name
,此時後臺就會直接報錯:3d
經過報錯信息咱們能夠知道:日誌
CommandLineRunner
在 Spring 容器起來以後開始執行,但此時 Tomcat 已經能夠正常接收請求。又因爲本案例中 CommandLineRunner 的運行時間過長,數據尚未初始化完成,因而程序就開始出錯了......code
那若是 CommandLineRunner
在執行過程當中報錯了會怎麼樣呢?blog
答案是:Spring 容器會自動關閉,應用會中止服務。資源
可能讀者會反駁小黑同窗說:「CommandLineRunner
在啓動時運行,若是 CommandLineRunner
運行報錯,那就發佈失敗唄。」get
其實還有更嚴重的......
廢話很少說,直接上具體案例,先看代碼:
@Slf4j @SpringBootApplication public class CommandLineRunnerDemoApp2 implements CommandLineRunner { public static void main(String[] args) { SpringApplication.run(CommandLineRunnerDemoApp2.class, args); } @Override public void run(String... args) throws Exception { log.info("start do commandLineRunner..."); // 模擬任務執行時長 TimeUnit.MINUTES.sleep(1); // 模擬運行過程當中出錯 int i = 1 / 0; log.info("do commandLineRunner end"); } }
運行日誌以下:
能夠看到,Spring 容器一開始正常運行,系統開始對外提供服務。一分鐘以後,CommandLineRunner
在執行過程當中報錯,致使 Spring 容器關閉,應用中止服務。
雖然上文中這些案例都很簡單,但小黑同窗在實際過程當中,還真就遇到過有同窗使用 CommandLineRunner
去初始化了一個很耗時的資源,而在初始化資源的時候,又不當心報錯了,因而應用就忽然中止了。不過幸運的是,此次只是發生在了測試環境,線上一切正常。