BSM
BSM

Reputation: 183

How to override spring Environment variables programmatically

I am using a bootstrap.properties file in my spring boot application. Is it possible to override the value of the property defined in bootstrap.properties through code.

I understand we can override the properties by passing value as a runtime argument while running the application.

Tried to set the variable value through System.setProperty() method.

The org.springframework.core.env.Environment does not have any methods to set the properties. Is there a way to add new property or override an existing property in spring core Environment.

Upvotes: 3

Views: 3890

Answers (1)

Ken Chan
Ken Chan

Reputation: 90427

Yes. All the current implementation of Environment is also a ConfigurableEnvironment which allows you to get its internal MutablePropertySources. After getting MutablePropertySources, you can use it to configure any searching precedence of any property .

For example , to set your own properties that always has the highest precedence , you can do :

if(environment instanceof ConfigurableEnvironment) {
        ConfigurableEnvironment env = (ConfigurableEnvironment)environment;

        Map<String,Object> prop = new HashMap<>();
        prop.put("foo", "fooValue");
        prop.put("bar", "barValue");

        MutablePropertySources mps = env.getPropertySources();
        mps.addFirst(new MapPropertySource("MyProperties", prop)); 

}

Then environment.getProperty("foo") should return fooValue.

Upvotes: 8

Related Questions