最近在做一個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));