spring boot 外部固定目录 配置文件

@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));

image.png

resources文件夹下创建一个文件夹名为META-INF,在里面创建一个spring.factories的文件,文件内容如下:

org.springframework.boot.env.EnvironmentPostProcessor=cc.ewell.dripping.product.baseinfo.common.config.LocalSettingsEnvironmentPostProcessor
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值