I am using Spring Boot 2 and by reading the doc about externalilzing properties here, I expect that I can override the value of a variable in application.properties by declaring an os environment variable of the same name.
So I tried as follows.
First, declare following 2 variables in src/main/resources/application.properties
my.prop = hello
myProp = hello
Next, create src/main/java/me/Main.java
with following content.
@SpringBootApplication
public class Main {
private static final Logger logger = LoggerFactory.getLogger(Main.class);
@Value("${my.prop}")
String myDotProp;
@Value("${myProp}")
String myProp;
@Value("${my.env.prop}")
String envDotProp;
@PostConstruct
public void test() {
logger.debug("my.prop : " + myDotProp);
logger.debug("myProp : " + myProp);
logger.debug("my.env.prop : " + envDotProp);
}
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
}
Now, using Windows Environment variables panel to declare 3 variables as in the picture below.
Finally, run mvn spring-boot:run
, and this is the result
2018-04-21 14:41:28.677 DEBUG 22520 --- [main] me.Main : my.prop : hello
2018-04-21 14:41:28.677 DEBUG 22520 --- [main] me.Main : myProp : world
2018-04-21 14:41:28.677 DEBUG 22520 --- [main] me.Main : my.env.prop : world
Please notice that
Spring can see the environment variables regardless of whether the have dot (.) in the variable name or not, as shown in myProp
and my.env.prop
Spring can override the value of a variable in application.properties
using the value of the os environment variable of the same name only if the name does not contain dot (.) as shown in myProp
and my.prop
: the value of myProp
has been successfully override to world
but the value of my.prop
stays hello
even I have os env variable my.prop
declared.
Is there a reason for this behavior and is there a way to configure Spring so that I can use dot in my properties variables as well as overriding them using os env variables?
Replace .
in your environment variables by _
.
For example if in Spring Boot the property is named my.env.prop
in order to override it use an environment variable named my_env_prop
and Spring does the conversion automatically.
The reason for the issue with .
is that some operating systems do not support .
in environment variables names.
Similar issue discussed here: How to set a Spring Boot property with an underscore in its name via Environment Variables?
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