Injecting property in Springboot using @Value annotation

Tags: , , ,



I am using Spring and Java for an application, and I want to use the @Value annotation to inject the value of the property, my use case is that I want first to check if that property exists as system property (so it takes priority), and otherwise default to a configuration property (existing in the properties file)

In the commented code you can see what I am trying to achieve, is that possible to default to something else that a simple string? If it is not, how can I achieve this?

//@Value("#{configProperties['local.datasource.username']}") THIS IS THE ORIGINAL CODE
//@Value("#{systemProperties['some.key'] ?: 'my default system property value'}") THIS IS HOW SPRING PROPOSE TO SET A DEFAULT VALUE
//@Value("#{systemProperties['some.key'] ?: #{configProperties['local.datasource.username']}}") THIS IS WHAT I WANT TO ACHIEVE, HOWEVER NOT COMPILING,
private String username;

Answer

What you are looking for are simple Property Palceholders.

While the Spring Expression Language supports the #{} syntax for rather complex expressions (ternary, calls, expressions, math), injecting property values and defaults is in most cases better done using a simple property placeholder ${value:defaultValue} approach:

@Property("${some.key:local.datasource.username}")
private String username;

Where some.key is being resolved (independent of its origin), and if that is null, Spring defaults to the value of local.datasource.username.

Please keep in mind, that even if some.key is present, Spring will throw an exception when it can’t resolve your default property.

See also:



Source: stackoverflow