32

Is there a way to set an empty list as default value for a property in Spring, something like:

@Value("${my.list.of.strings :" + new ArrayList<>() + "}")
private List<String> myList;

Obviously not new ArrayList, but I need an empty list there instead.

Andrei Roba
  • 2,156
  • 2
  • 16
  • 33

4 Answers4

32

After taking a look at SpEL specification and combined with @javaguy's answer I came up with this:

@Value("${my.list.of.strings:}#{T(java.util.Collections).emptyList()}")
private List<String> myList;
Andrei Roba
  • 2,156
  • 2
  • 16
  • 33
  • your answer is helpful but incomplete, since the value annotation points to a property in the first place (which should be initialized when not present - otherwise it leads to an IllegalArgumentException) – Andrei Roba Mar 21 '17 at 08:27
  • I have used that for zero sized `list` in my project and did not get any `IllegalArgumentException` – Vasu Mar 21 '17 at 08:29
  • don't know about your code but mine breaks if I specify a property where there's no default value and does not come up in any property file – Andrei Roba Mar 21 '17 at 08:37
  • Seems it works, but no idea why. I would expect that empty list directly after colon and not after closing parenthesis }. – Ondřej Stašek Mar 22 '18 at 12:59
  • Whit what logic this work? How $ and # in the same annotation can work like this? It seems to work , but why? could you please explain? @RobyRodriguez – artas Oct 13 '21 at 16:16
  • It's really much simpler with @sf_ 's answer – Crystark Jun 17 '22 at 13:15
20

Actually, in the current Spring versions works just one symbol : with an empty defaultvalue.

The full example that I'm using:

@Value("${my.custom.prop.array:}")
private List<Integer> myList;

To be sure and safer I also adding init to the List variable:

@Value("${my.custom.prop.array:}")
private List<Integer> myList = new ArrayList<>();
sf_
  • 1,138
  • 2
  • 13
  • 28
  • 1
    This solution requires `ConversionServiceFactoryBean` as reported here: https://stackoverflow.com/a/29970335/685806 – Pino Mar 30 '20 at 10:38
4
@Value("#{T(java.util.Arrays).asList('${my.list.of.strings:}')}")
private List<String> myList;

works for me, using Spring 5.0.x (gives empty list, if your my.list.of.strings property is not configured in context)

afterwards you can easily do something like

CollectionUtils.isNotEmpty(myList)
Philipp Wirth
  • 902
  • 8
  • 11
2

You can use Collections.emptyList() to populate the empty list object with zero size as shown below:

@Value("#{T(java.util.Collections).emptyList()}")
private List<String> myList;

This will give you a zero sized myList

Vasu
  • 21,832
  • 11
  • 51
  • 67
  • what's the significance of 'T' here ? – flash Dec 04 '20 at 19:04
  • @flash, it is allowing to reinterpret the parameter as a class object. Next the static method `.emptyList()` is called on `java.util.Collections.class` class – msangel Jan 29 '21 at 15:31