[Spring Boot] Create application.properties Default Value from Environment Variables

Usually we have below code on application.properties

hello=${HELLO_ENV_VARIABLE}

It means that we are setting the value of variable “hello” from “HELLO_ENV_VARIABLE” which are being passed on thru environment variables. Which later on we can set on IntelliJ

Later on, we can call it from our Java Class,

@RestController
public class HelloWorldController {

    @Value("${hello}")
    private String hello;

    @GetMapping("/")
    public Map index() {
        return new HashMap() {{
            put("hello", hello);
        }};
    }
}

We can also create a default value, in case of “HELLO_ENV_VARIABLE” is not being set,

hello=${HELLO_ENV_VARIABLE:something not world}

But what most people forgot is that we can also create a default value from other environment variable

hello=${HELLO_ENV_VARIABLE:${HELLO_ENV_VARIABLE_BACKUP}}

And set it up on IntelliJ

It will result in something like this,

{"hello":"this is a backup variable"}

Leave a Comment

Your email address will not be published.