Optional environment variables in Spring app

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)