springboot下自定义读取任意位置的配置文件


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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

qq_37749055

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值