@PropertySource(value={"file:/config/config.properties"})
public class Application {
}
注意必須要加 file: 開頭 配置文件 必須 properties 格式 yml
文件不支持
LocalSettingsEnvironmentPostProcessor
package cc.ewell.dripping.product.baseinfo.common.config;
import lombok.extern.log4j.Log4j;
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;
@Log4j
public class LocalSettingsEnvironmentPostProcessor implements EnvironmentPostProcessor{
private static final String LOCATION = "\\dripping\\baseinfo.properties";
@Override
public void postProcessEnvironment(ConfigurableEnvironment configurableEnvironment, SpringApplication springApplication) {
File file = new File(System.getProperty("EWELL_ENV"), LOCATION);
//本地環境變量 EWELL_ENV 設置父目錄
if (file.exists()) {
log.info(" File "+System.getProperty("EWELL_ENV")+LOCATION);
MutablePropertySources propertySources = configurableEnvironment.getPropertySources();
Properties properties = loadProperties(file);
log.info(" Properties "+properties.toString());
propertySources.addFirst(new PropertiesPropertySource("Config", properties));
}else {
log.warn(" File "+System.getProperty("EWELL_ENV")+LOCATION+" IS NOT EXIST");
}
}
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);
}
}
}
這裏的 addFirst 方法 是先加着外部配置文件
addLast 方法 是後加着外部配置文件 配置文件加載的順序 是後面加載的配置文件存在同樣的配置 會覆蓋先加載的。
propertySources.addLast(new PropertiesPropertySource("Config", properties));
resources文件夾下創建一個文件夾名爲META-INF,在裏面創建一個spring.factories的文件,文件內容如下:
org.springframework.boot.env.EnvironmentPostProcessor=cc.ewell.dripping.product.baseinfo.common.config.LocalSettingsEnvironmentPostProcessor