Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ;(

like image 919
JOKe Avatar asked Sep 25 '14 08:09

JOKe


People also ask

How do I refresh properties in spring boot?

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.

How do you update application properties in spring boot dynamically?

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 .

How reload properties file without restarting server in Spring?

include=refresh: this is actuator property which will help us to refresh the properties without restarting the server.

How do you use Configurableenvironment?

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.


2 Answers

// ConfigurableEnvironment env
MutablePropertySources propertySources = env.getPropertySources();
Map<String, Object> map = new HashMap<>();
map.put(myObject.getKey(),
            myObject.getQuery());
propertySources
            .addFirst(new MapPropertySource("newmap", map));
like image 147
user6631150 Avatar answered Sep 28 '22 09:09

user6631150


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.

like image 37
mgibson Avatar answered Sep 28 '22 09:09

mgibson