15

Is it possible to inject a null or blank string as the default value that will be used in a spring file if the property is not specified? Currently the best I have is

<constructor-arg index="1" value="@{data.url:&quot;&quot;}"/>

which resolves to "" in code

qwerty
  • 3,801
  • 2
  • 28
  • 43
  • 1
    I think just `` should work. In case you need the index you may add it. Maybe I am not getting your question right? – Ivaylo Strandjev Dec 11 '12 at 09:35
  • will always send an empty string. I'm interested in an empty string only if one is not specified in the associated properties file. Please see http://stackoverflow.com/a/2534949/222867 – qwerty Dec 11 '12 at 09:44

5 Answers5

15

Empty-Elvis works for me...

@Value("${http.proxyHost?:}")
public String proxyHost = null;
RMHarris157
  • 269
  • 2
  • 9
  • Eclipse Oxygen generates an expression expected warning when I do this. It does work, though. I'm guessing this is an Eclipse issue. – David Bradley Jul 25 '18 at 17:13
13

Have you tried using SpEL? Something like this maybe:

<constructor-arg index="1" value="#{'${data.url}'==null?'':'${data.url}'}"/>

Update

I just remembered that there's an easier way (as nicely described here). Try:

<constructor-arg index="1" value="${data.url:''}"/>
Marcel Stör
  • 22,695
  • 19
  • 92
  • 198
13

This will do the trick if you are using annotations in your source:

@Value("${data.url:#{null}}")
private String dataUrl;
BrentR
  • 878
  • 6
  • 20
0
  1. If you want to set value as null:
@Value("${data.url:#{null}}")
private String dataUrl;
  1. If you want to set value as empty string:
@Value("${data.url:}")
private String dataUrl;
0

To inject an empty string as the default value, you can use the @Value annotation with the defaultValue attribute

@Value("${data.url:}")
private String dataUrl;

you can also define the property like:

@Value("${data.url:#{null}}")
private String dataUrl;