1. 程式人生 > >SpringBoot 打包為war包啟動時匯入外部配置檔案

SpringBoot 打包為war包啟動時匯入外部配置檔案

最近在做一個SpirngBoot的專案,要求伺服器部署的時候使用tomcat啟動war包的時候需要匯入一個指定位置的application.properties檔案。在網上查找了相關的問題之後,發現大部分都是基於jar包的,同樣的方法war包下並不適用。
後來發現了一個方法,可以為完美解決這個問題。
這裡寫圖片描述
在你的專案資料夾下,建立一個configuration資料夾用於儲存各種SpringBoot的配置檔案,然後新建一個Java類LocalSettingsEnvironmentPostProcessor。

package com.altynai.xxxxxx.configuration;

import org.springframework
.boot.SpringApplication; import org.springframework.boot.env.EnvironmentPostProcessor; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.MutablePropertySources; import org.springframework.core.env.PropertiesPropertySource; import org.springframework.core
.io.FileSystemResource; import org.springframework.core.io.support.PropertiesLoaderUtils; import java.io.File; import java.io.IOException; import java.util.Properties; public class LocalSettingsEnvironmentPostProcessor implements EnvironmentPostProcessor{ private static final String LOCATION = "C:\\xxxx\\application.properties"
; @Override public void postProcessEnvironment(ConfigurableEnvironment configurableEnvironment, SpringApplication springApplication) { File file = new File(LOCATION); // File file = new File(System.getProperty("user.home"), LOCATION); // System.out.println("user.home" + System.getProperty("user.home")); if (file.exists()) { MutablePropertySources propertySources = configurableEnvironment.getPropertySources(); // System.out.println("Loading local settings from " + file.getAbsolutePath()); Properties properties = loadProperties(file); // System.out.println(properties.toString()); propertySources.addFirst(new PropertiesPropertySource("Config", properties)); } } private Properties loadProperties(File f) { FileSystemResource resource = new FileSystemResource(f); try { return PropertiesLoaderUtils.loadProperties(resource); } catch (IOException ex) { throw new IllegalStateException("Failed to load local settings from " + f.getAbsolutePath(), ex); } } }

這個java類的作用就是根據指定的配置檔案路徑,讀取檔案,新增到程式執行的環境中。注意,根據我的測試,這裡匯入的外部配置檔案只能是.properties的檔案,如果是.yml的話會有問題。
然後在你的resources資料夾下建立一個資料夾名為META-INF,在裡面建立一個spring.factories的檔案,檔案內容如下:

org.springframework.boot.env.EnvironmentPostProcessor=com.altynai.xxxxx.configuration.LocalSettingsEnvironmentPostProcessor

這個檔案的作用就是設定SpringBoot服務啟動的時候呼叫我們剛才寫的那個Java類。

至此,你的war包在使用tomcat啟動的時候就應該可以讀取制定位置的外部檔案了。我的檔案結構如下,僅供參考
這裡寫圖片描述
這裡還需要說明的是假設你原本的配置檔案的設定屬性與匯入了外部配置檔案的設定屬性重複了最終系統執行起來使用的是哪一個?
答案是,看兩個配置檔案加入程式環境的先後順序,後面的會覆蓋前面的。
上面的Java類中有這個一段程式碼,這裡的意思就是,外部的檔案是最先匯入的。

 propertySources.addFirst(new PropertiesPropertySource("Config", properties));

如果設定為下面的這個

 propertySources.addLast(new PropertiesPropertySource("Config", properties));

則表示最後匯入外部配置檔案。