有時需要愛項目啟動時, 去加載一些配置文件什么的, 可以使用監聽器的方式加載, 這是可以通過實現接口 CommandLineRunner來實現需求:
Spring Boot應用程序在啟動后,會遍歷CommandLineRunner接口的實例並運行它們的run方法。也可以利用@Order注解(或者實現Order接口)來規定所有CommandLineRunner實例的運行順序。
package com.iwhere.run; import org.springframework.boot.CommandLineRunner; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; /** * 該類可以在springboot啟動是, 進行操作 * @Order: 啟動時執行的順序, 小的優先執行 * @author wenbronk * @time 2017年4月6日 下午1:40:17 2017 */ @Component @Order(value=2) public class MyStartupRunner implements CommandLineRunner { /** * 執行的方法, * args為執行時傳入的參數, * 可用: SpringApplication.run(App.class, new String[]{"hello,","林峰"}); * 或者: eclipse中給java應用傳args參數的方法如下: 1、先寫好Java代碼,比如文件名為IntArrqy.java; 2、在工具欄或菜單上點run as下邊有個Run Configuration; 3、在彈出窗口點選第二個標簽arguments; 4、把你想輸入的參數寫在program argumenst就可以了,多個參數使用空格隔開。 完成后點run即可通過運行結果看到參數使用情況了。 */ @Override public void run(String... arg0) throws Exception { System.out.println("開機服務執行的操作...."); } }
原文地址: http://412887952-qq-com.iteye.com/blog/2292577