在Spring配置中初始化空的数组列表? [英] Initialize empty arraylists in Spring configuration?

查看:427
本文介绍了在Spring配置中初始化空的数组列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Spring,并且读了《 Spring in Action》一书.我想知道您是否应该注入一个空的arraylist(如果可能的话)还是像下面的示例那样创建它?

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?

public class StackOverflow {

    private List<Car> cars;

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

推荐答案

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

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.

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

如果要快速设置空列表以防止出现空指针问题,则只需使用Collections.emptyList().您也可以按如下所示内联"进行操作.请注意,尽管Collections.emptyList()返回了不可修改的列表.

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.

public class StackOverflow {

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

您还需要汽车的吸气剂和吸气剂,以便能够从Spring XML中使用它.

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

这篇关于在Spring配置中初始化空的数组列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆