1

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;
Clijsters
  • 4,031
  • 1
  • 27
  • 37
fgonzalez
  • 3,787
  • 7
  • 45
  • 79
  • 1
    Instead of using the elvis operator, SpEL supports defaults with `:` IIRC on your third example the first `#` should be a `$` and imho the expressions don't have to be of collective types: `${some.key:local.datasource.username}` – Clijsters Jul 01 '20 at 14:57
  • 1
    That worked! thanks, should you add the comment as answer in order to set this as resolved? – fgonzalez Jul 01 '20 at 15:05
  • Glad to hear, I wrote an answer and added some additional information. – Clijsters Jul 01 '20 at 15:26

1 Answers1

2

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:

Clijsters
  • 4,031
  • 1
  • 27
  • 37
  • 1
    For clarity, `${...}` is NOT SpEL. They are property placeholders that existed for many years before SpEL was introduced. – Gary Russell Jul 01 '20 at 15:53
  • Yes, that's correct and described in the question I referred. I edited the answer to make it more clear. – Clijsters Jul 01 '20 at 16:10