import org.apache.commons.lang3.StringUtils;
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 org.springframework.util.Assert;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
/**
* @Description 自定义配置文件路径加载
* @Date 2019/12/08 2·:40
* @author 杨光
*/
public class ConfEnvironmentPostProcessor implements EnvironmentPostProcessor {
/**
* 配置文件的绝对路径
*/
private static final String PROFILES_CONF_PATH = "properties.path";
/**
* 无特殊要求 但不能为空或null
*/
private static final String MAP_KEY = "application.properties";
/**
* @Description 加载配置文件方法
*/
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
try{
//从默认配置文件中获得外部文件路径
String rootPath = environment.getProperty(PROFILES_CONF_PATH);
Assert.hasText(rootPath, "外部配置文件路径不能为空");
MutablePropertySources propertySources = environment.getPropertySources();
File defaultFile = new File(rootPath);
Assert.isTrue(defaultFile.exists(),"外部配置文件不存在"+rootPath);
Properties defaultProperties = loadProperties(defaultFile);
//加入
propertySources.addFirst(new PropertiesPropertySource(MAP_KEY, defaultProperties));
System.out.println("加载配置文件:" + rootPath);
} catch (IOException e){
e.printStackTrace();
Assert.isTrue(false,"文件读取错误"+e.getMessage());
}
}
/**
* @Description 加载配置文件
*/
private Properties loadProperties(File f) throws IOException{
FileSystemResource resource = new FileSystemResource(f);
return PropertiesLoaderUtils.loadProperties(resource);
}
}
2.在resources下加入包META-INF/spring.factories
org.springframework.boot.env.EnvironmentPostProcessor=com.eca.mind.bmw.ConfEnvironmentPostProcessor