如何以编程方式覆盖 spring 环境变量

BSM*_*BSM 3 spring spring-boot

我在 Spring Boot 应用程序中使用 bootstrap.properties 文件。是否可以通过代码覆盖 bootstrap.properties 中定义的属性值。

我知道我们可以通过在运行应用程序时将值作为运行时参数传递来覆盖属性。

尝试通过 System.setProperty() 方法设置变量值。

org.springframework.core.env.Environment 没有任何方法来设置属性。有没有办法在 spring core 环境中添加新属性或覆盖现有属性。

Ken*_*han 8

是的。所有当前的实现Environment也是一个ConfigurableEnvironment允许您获取其内部的MutablePropertySources. 获取后 MutablePropertySources,您可以使用它来配置任何属性的搜索优先级。

例如,要设置始终具有最高优先级的您自己的属性,您可以执行以下操作:

if(environment instanceof ConfigurableEnvironment) {
        ConfigurableEnvironment env = (ConfigurableEnvironment)environment;

        Map<String,Object> prop = new HashMap<>();
        prop.put("foo", "fooValue");
        prop.put("bar", "barValue");

        MutablePropertySources mps = env.getPropertySources();
        mps.addFirst(new MapPropertySource("MyProperties", prop)); 

}
Run Code Online (Sandbox Code Playgroud)

然后environment.getProperty("foo")应该返回fooValue