如何在 Spring 的 ConfigurableEnvironment 中更改/更新/删除属性

JOK*_*OKe 7 spring spring-mvc

在 Spring 中,您可以使用注入 Environment 对象来读取所有环境属性

@Resource
private org.springframework.core.env.Environment environment;
Run Code Online (Sandbox Code Playgroud)

所以问题是我可以以编程方式更改某些属性的值吗?

我看到的唯一解决方法是获取所有拥有此属性的 MutablePropertySource。从环境中完全删除此源并添加一个新的 PropertySource,其中包含前一个 + 更改的(或删除的)的所有属性。

但是这看起来很难看,而且会很慢;(

小智 18

// ConfigurableEnvironment env
MutablePropertySources propertySources = env.getPropertySources();
Map<String, Object> map = new HashMap<>();
map.put(myObject.getKey(),
            myObject.getQuery());
propertySources
            .addFirst(new MapPropertySource("newmap", map));
Run Code Online (Sandbox Code Playgroud)