springboot 加载外部配置文件

原文链接

摘要: springboot 引入非当前工程外部文件

开发springboot应用时经常有多个配置文件,开发的,测试的,生产环境的。 而生产环境的敏感数据又不希望泄露出去,所有想看看springboot有没有办法加载外部文件的办法。
因为springboot 默认加载配置文件的位置是

classpath:/,classpath:/config/,file:./,file:./config/

打包jar运行也不方便修改jar内部数据,一开始准备自己写个加载方法,后来看到spring的加载器配置文件ConfigFileApplicationListener里面有加载文件的功能,刚好不用自己写了。
spring定义的外部文件名称参数

public static final String CONFIG_ADDITIONAL_LOCATION_PROPERTY = "spring.config.additional-location";

在这里有使用

private Set<String> getSearchLocations() {
            if (this.environment.containsProperty(CONFIG_LOCATION_PROPERTY)) {
                return getSearchLocations(CONFIG_LOCATION_PROPERTY);
            }
            Set<String> locations = getSearchLocations(
                    CONFIG_ADDITIONAL_LOCATION_PROPERTY);
            locations.addAll(
                    asResolvedSet(ConfigFileApplicationListener.this.searchLocations,
                            DEFAULT_SEARCH_LOCATIONS));
            return locations;
        }


private Set<String> getSearchLocations(String propertyName) {
            Set<String> locations = new LinkedHashSet<>();
            if (this.environment.containsProperty(propertyName)) {
                for (String path : asResolvedSet(
                        this.environment.getProperty(propertyName), null)) {
                    if (!path.contains("$")) {
                        path = StringUtils.cleanPath(path);
                        if (!ResourceUtils.isUrl(path)) {
                            path = ResourceUtils.FILE_URL_PREFIX + path;
                        }
                    }
                    locations.add(path);
                }
            }
            return locations;
        }

然后断点调试了下,发现数据是从系统变量里面取的,所以使用方式就是设置spring.config.additional-location到系统变量中,多个可以用逗号隔开。

java -jar -Dspring.config.additional-location=/home/application-xxx.properties  xxx.jar 

需要注册该文件是最先加载,也就是里面的数据会被其他文件的覆盖

第二个办法是设置环境变量spring.config.location,因为前面加载逻辑是先判断该变量有没有设置,然后再加载默认的

spring.config.location=/自定义文件或目录,classpath:/,classpath:/config/,file:./,file:./config/

这样就可以灵活控制加载的先后顺序了

猜你喜欢

转载自blog.csdn.net/weixin_40581980/article/details/81630361