Can I set null as the default value for a @Value in Spring?
I'm currently using the @Value Spring 3.1.x annotation like this:
@Value("${stuff.value:}")
private String value;
This puts an empty String into the variable if the attribute is not present. I would like to have null as the default instead of an empty String. Of course I also want to avoid an error when the property stuff.value is not set.
This is really old, but you can use Spring EL now, e.g.
@Value("${stuff.value:#{null}}")
See this question.
You must set the nullValue of the PropertyPlaceholderConfigurer. For the example I'm using the string @null
but you can also use the empty string as nullValue.
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<!-- config the location(s) of the properties file(s) here -->
<property name="nullValue" value="@null" />
</bean>
Now you can use the string @null
to represent the null
value
@Value("${stuff.value:@null}")
private String value;
Please note: The context name space doesn't support the null value at the moment. You can't use
<context:property-placeholder null-value="@null" ... />
Tested with Spring 3.1.1
Thanks to @vorburger:
@Value("${email.protocol:#{null}}")
String protocol;
will set the string value at null without any other configurations.