概述

我们知道,在Spring boot中可以通过xml或者@ImportResource 来引入自己的配置文件,但是这里有个限制,必须是本地,而且格式只能是 properties(或者 yaml)。那么,如果我们有远程配置,如何把他引入进来来呢。

第一种方式

这外一种方法,相对更简单些,但是相对没那么“优雅”。就是通过EnvironmentPostProcessor接口把我们自定义的propertySource加入environment中,

复制代码
public class MyEnvironmentPostProcessor implements EnvironmentPostProcessor {
    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        MyPropertySource propertySource = new MyPropertySource("myPropertySource");

        Map<String, String> propertyMap = new HashMap<>();
        propertyMap.put("myName", "lizo");
        propertySource.setProperty(propertyMap);
        environment.getPropertySources().addLast(propertySource);
    }
}
复制代码

同时需要在META-INFO/spring.factories中加入

org.springframework.boot.env.EnvironmentPostProcessor=com.lizo.MyEnvironmentPostProcessor

第二种方式

第二种方式可能相对比较复杂一点,其实是参考Sprng cloud中的做法,其实也只需要3步

第一步,编写PropertySourceLocator

PropertySourceLocator 其实就是用来定位我们前面的PropertySource,需要重写的方法只有一个,就是返回一个PropertySource对象,例如,

public class EnvConfigurer implements PropertySourceLocator {
@Override
public PropertySource<?> locate(Environment environment) {
Map<String, Object> map = new HashMap<>();
initSysConfig(environment, map, "KETTY_IP", NetUtils.getLocalHost());
return new MapPropertySource("myEnv", map);
}

private void initSysConfig(Environment environment, Map<String, Object> map, String key, String defaultValue) {
String propValue = environment.getProperty(key);
if(StringUtils.isEmpty(propValue)) {
propValue = defaultValue;
}
map.put(key, propValue);
}
}

第三步,让PropertySourceLocator生效

创建/更新 META-INFO/spring.factories(如果做过自定义Spring boot开发的都知道这个文件)

org.springframework.cloud.bootstrap.BootstrapConfiguration=\
com.lizo.EnvConfigurer 

简单来说就是给Spring Boot说,这个是一个启动配置类(一种优先级很高的配置类)。

编写测试

我们在application配置文件中,引入这个变量呢,例如在application.properties中

my.name=${KETTY_IP}

同样,结果也是能够生效的

myName就是上面在PropertySourceLocator中写进去的配置属性。运行程序,可以看见确实是可以正确输出。

小结

上面只是抛砖引玉,这样无论是哪里的数据源,都可以通过这种方式编写,把配置交给Spring 管理。这样再也不怕在本地配置文件中出现敏感信息啦,再也不怕修改配置文件需要登录每一个机器修改啦。

转载:https://www.cnblogs.com/lizo/p/7683300.html