I have the following in a Spring bean:
@Value("${myValue}")
private String value;
The value is correctly injected. However, the variable needs to be optional, it is passed in as a command line parameter (which is then added to the Spring context using a SimpleCommandLinePropertySource), and this argument will not always exist.
I have tried both the following in order to provide a default value:
@Value("${myValue:}")
@Value("${myValue:DEFAULT}")
but in each case, the default argument after the colon is injected even when there is an actual value - this appears override what Spring should inject.
What is the correct way to specify that @Value is not required?
Thanks
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!
来源:https://stackoverflow.com/questions/23348061/how-to-define-value-as-optional