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 ;(
Reloading Properties by Actuator and Cloud Thus, we need Spring Cloud to add a /refresh endpoint to it. This endpoint reloads all property sources of Environment, and then publishes an EnvironmentChangeEvent. Spring Cloud has also introduced @RefreshScope, and we can use it for configuration classes or beans.
You can do something like reading the properties file using FileInputStream into a Properties object. Then you will be able to update the properties. Later you can write back the properties to the same file using the FileOutputStream .
include=refresh: this is actuator property which will help us to refresh the properties without restarting the server.
Method Summary. Add a profile to the current set of active profiles. Return the PropertySources for this Environment in mutable form, allowing for manipulation of the set of PropertySource objects that should be searched when resolving properties against this Environment object. Return the value of System.
// ConfigurableEnvironment env
MutablePropertySources propertySources = env.getPropertySources();
Map<String, Object> map = new HashMap<>();
map.put(myObject.getKey(),
myObject.getQuery());
propertySources
.addFirst(new MapPropertySource("newmap", map));
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With