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
andmy.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 inmyProp
andmy.prop
: the value ofmyProp
has been successfully override toworld
but the value ofmy.prop
stayshello
even I have os env variablemy.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?
MY_ENV_PROP
,MY_PROP
andMYPROP
. – g00glen00b