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

Viewed 121562

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.

5 Answers

In case you need to inject an empty (0 length) "" string as @Value default - use SPEL (spring expression language) as follows:

@Value("${index.suffix:#{''}}") 
private String indexSuffix;

#{''} just gets you an empty string as injected @Value's default.

by yl

Related