Spring @Value empty list as default

元气小坏坏 提交于 2021-01-20 15:55:52

问题


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.


回答1:


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;



回答2:


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<>();



回答3:


@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)



回答4:


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



来源:https://stackoverflow.com/questions/42920606/spring-value-empty-list-as-default

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!