Java 在 Spring 配置中初始化空数组列表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9663660/
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-08-16 05:49:04  来源:igfitidea点击:

Initialize empty arraylists in Spring configuration?

javaspringjakarta-ee

提问by LuckyLuke

I am learning Spring and I read the Spring in Action book. I wonder if you are supposed to inject an empty arraylist (if that is possible) or create it like the example below?

我正在学习 Spring,并阅读了 Spring in Action 一书。我想知道你是应该注入一个空的数组列表(如果可能的话)还是像下面的例子一样创建它?

public class StackOverflow {

    private List<Car> cars;

    public StackOverflow() {
        cars = new ArrayList<Car>();
    }
}

采纳答案by Adam

You can inject an empty list like this, however this is probably unnecessary, unless you're trying to setup an example template spring XML config perhaps.

您可以像这样注入一个空列表,但这可能是不必要的,除非您尝试设置示例模板 spring XML 配置。

<property name="cars">
  <list></list>
</property>

If you want a quick way of setting empty lists to prevent null pointer problems, then just use Collections.emptyList(). You can also do it "inline' as follows. Note though that Collections.emptyList() returns an unmodifiable list.

如果您想快速设置空列表以防止空指针问题,那么只需使用 Collections.emptyList()。您也可以按如下方式“内联”执行此操作。请注意 Collections.emptyList() 返回一个不可修改的列表。

public class StackOverflow {

    private List<Car> cars = Collections.emptyList();

You'll also need getters and setters for cars to be able to use it from spring XML.

您还需要汽车的 getter 和 setter 才能从 spring XML 使用它。

回答by Richard Grossman

You can make like this

你可以这样

<util:list id="emptyList"
           value-type="Cars">
</util:list>

With is something like

与是类似的东西

public static interface Car
{
   String getName();
}

回答by Omri Sivan

You can use autowiring to inject all Car types that are Spring managed, as long as your class (in this case StackOverflow) is instantiated via Spring:

您可以使用自动装配来注入 Spring 管理的所有 Car 类型,只要您的类(在本例中为 StackOverflow)通过 Spring 实例化:

@Autowire
private List<Car> cars;

回答by burcakulug

I had a problem with this answer. I guess Spring complains when you open a collection, but don't add any items in it as given in the example in that post. If that doesn't work, try the one below. It worked for me for util:set.

我对这个答案疑问。我猜当您打开一个集合时,Spring 会抱怨,但不要像该帖子中的示例中给出的那样在其中添加任何项目。如果这不起作用,请尝试以下方法。它对我有用util:set

<util:list id="emptyList" value-type="Cars"/>