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.
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
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.