Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional environment variables in Spring app

In my Spring Boot app's application.properties I have this definition:

someProp=${SOME_ENV_VARIABLE} 

But this is an optional value only set in certain environments, I use it like this

@Value("${someProp:#{null}}") private String someProp; 

Surprisingly I get this error when the env. var doesn't exist
Could not resolve placeholder 'SOME_ENV_VARIABLE' in string value "${SOME_ENV_VARIABLE}"
I was expecting Spring to just set a blank value if not found in any PropertySource.

How to make it optional?

like image 318
Maxime Laval Avatar asked Nov 30 '17 18:11

Maxime Laval


2 Answers

Provide a default value in the application.properties

someProp=${SOME_ENV_VARIABLE:#{null}} 

When used like @Value("${someProp}), this will correctly evaluate to null. First, if SOME_ENV_VARIABLE is not found when application.properties is being processed, its value becomes the string literal "#{null}". Then, @Value evaluates someProp as a SpEL expression, which results in null. The actual value can be verified by looking at the property in the Environment bean.

This solution utilizes the default value syntax specified by the PlaceholderConfigurerSupport class

Default property values can be defined globally for each configurer instance via the properties property, or on a property-by-property basis using the default value separator which is ":" by default and customizable via setValueSeparator(String).

and Spring SpEL expression templating.

From Spring Boot docs on externalized configuration

Finally, while you can write a SpEL expression in @Value, such expressions are not processed from Application property files.

like image 148
Robert Farley Avatar answered Sep 28 '22 06:09

Robert Farley


This work for me:

spring.datasource.url=jdbc:mysql://${DB_IP:localhost}:3306/app spring.datasource.username=${SPRING_DATASOURCE_USERNAME:mylocaluser} spring.datasource.password=${SPRING_DATASOURCE_PASSWORD:localpass} 
like image 30
Barrrettt Avatar answered Sep 28 '22 06:09

Barrrettt