Spring @Value annotation is used to assign default values to variables and method arguments.
For the record, the specification of what a POJO is, means that the class cannot contain pre-specified annotations. So even in another world where @Value could work on a non-spring bean, it would still, by definition, break the POJO aspect of the class.
@Value with Constructor methodThe annotation @Value can inject values in constructor while creating the instance of a class in the bean.
No, this is not (directly) possible. The default value of an annotation property must be a compile-time constant.
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!
I guess you are you using multiple context:property-placeholder/ declarations?
If so, this is a known issue since 2012, but not fixed, apparently due to both lack of interest and no clean way of fixing it. See https://github.com/spring-projects/spring-framework/issues/14623 for discussion and some ways to work around it. It's explained in an understandable way by http://www.michelschudel.nl/wp/2017/01/25/beware-of-multiple-spring-propertyplaceholderconfigurers-and-default-values/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With