Can I set null as the default value for a @Value in Spring?

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.


This is really old, but you can use Spring EL now, e.g.

@Value("${stuff.value:#{null}}")

See this question.