问题
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