Spring @ Insert empty default list

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

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

      

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

+9


source to share


4 answers


After looking at the Spel spec, and combined with @ javaguy's answer, I came up with the following:



@Value("${my.list.of.strings:}#{T(java.util.Collections).emptyList()}")
private List<String> myList;

      

+14


source


You can use Collections.emptyList()

to fill an empty list object with zero size like below:

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

      



This will give you a null value myList

+1


source


@Value("#{T(java.util.Arrays).asList('${my.list.of.strings:}')}")
private List<String> myList;

      

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

after that you can easily do something like

CollectionUtils.isNotEmpty(myList)

      

0


source


Works fine.

    @Value("#{T(org.apache.commons.lang3.StringUtils).split('${my.list.of.strings:}', ',')}")
    private List<String> myList;

      

0


source







All Articles