How to define @Value as optional
What is the correct way to specify that @Value is not required?
Working on the assumption that by 'not required' you mean null
then...
You have correctly noted that you can supply a default value to the right of a :
character. Your example was @Value("${myValue:DEFAULT}")
.
You are not limited to plain strings as default values. You can use SPEL expressions, and a simple SPEL expression to return null
is:
@Value("${myValue:#{null}}")
If you are using Java 8, you can take advantage of its java.util.Optional
class.
You just have to declare the variable following this way:
@Value("${myValue:#{null}}")
private Optional<String> value;
Then, you can check whether the value is defined or not in a nicer way:
if (value.isPresent()) {
// do something cool
}
Hope it helps!