问题
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 default
value.
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