設定springboot專案預設不載入application.properties檔案
阿新 • • 發佈:2018-12-21
我們都知道,springboot專案啟動時會預設把classpath目錄下的application.properties檔案作為系統配置檔案,但如果我們想根據自己的意願載入別的檔案,比如beans.xml、config.xml等等。
設想一個場景,專案中有四個環境的配置,如開發、測試、壓測和生產,分別對應下圖中標識的四個檔案,通過application.properties中的spring.profiles.active屬性來指定不同的環境。比如spring.profiles.active=dev說明專案啟動時讀取的是application-dev.properties中的配置。
但是,在某種情況下我們不想通過spring.profiles.active來決定載入哪個檔案,那麼怎麼做呢?
可通過下面的程式碼實現:
@SpringBootApplication public class SpringbootTestApplication { public static void main(String[] args) throws IOException { Properties properties = new Properties(); //這裡指定載入的是application-uat.properties檔案的配置 InputStream inputStream = SpringbootTestApplication.class.getClassLoader().getResourceAsStream("application-uat.properties"); properties.load(inputStream); SpringApplication app = new SpringApplication(SpringbootTestApplication.class); app.setDefaultProperties(properties); app.run(args); } }
但是,僅僅這樣做還不夠,我們要把application.properties檔名字修改一下,如果不修改那麼無論程式怎麼改動,預設載入的還是application.properties檔案。