3
votes

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.

enter image description here

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

  1. 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

  2. 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?

1
When using system environment variables, it's recommended to use uppercase symbols though, so you should set MY_ENV_PROP, MY_PROP and MYPROP.g00glen00b

1 Answers

1
votes

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?