How to change/update/delete a property in ConfigurableEnvironment of Spring

て烟熏妆下的殇ゞ 提交于 2020-01-11 10:07:10

问题


In Spring you can use inject an Environment object to read all environment properties

@Resource
private org.springframework.core.env.Environment environment;

So the question is can I programatically change an value of some property?

The only workaround I see is to get the all MutablePropertySource that holds this property. to remove this source completely from the environment and to add a new PropertySource that contains all properties of the previous one + the changed one (or the removed one).

However this looks ugly and will be slow ;(


回答1:


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



回答2:


Note that 'newmap' in the above answer by @user6631150 is the name of the property file where you want to update/add values.

Also not that this does not change the property file on disk, it only updates it in memory.

Meaning: if you have a property file newmap.properties located in C:/user/app_dir/newmap.properties and you modify it with the above code, you will not see changes in the file at this location. The changes will be in memory only. If your application restarts, no changes will be at the said location.



来源:https://stackoverflow.com/questions/26033779/how-to-change-update-delete-a-property-in-configurableenvironment-of-spring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!