java Spring @Value 空列表默认

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42920606/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 06:57:08  来源:igfitidea点击:

Spring @Value empty list as default

javaspringspring-annotations

提问by Roby Rodriguez

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

有没有办法在 Spring 中将空列表设置为属性的默认值,例如:

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

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

显然不是新的 ArrayList,但我需要一个空列表。

回答by Roby Rodriguez

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

在查看了 SpEL 规范并结合@javaguy 的回答后,我想出了这个:

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

回答by Philipp Wirth

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

对我有用,使用 Spring 5.0.x(如果您的 my.list.of.strings 属性未在上下文中配置,则给出空列表)

afterwards you can easily do something like

之后你可以轻松地做类似的事情

CollectionUtils.isNotEmpty(myList)

回答by sf_

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

实际上,在当前的 Spring 版本中,只有一个:带有empty default值的符号。

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:

为了确保安全,我还将 init 添加到 List 变量中:

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

回答by developer

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

您可以使用Collections.emptyList()零大小填充空列表对象,如下所示:

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

This will give you a zero sized myList

这会给你一个零大小 myList