【问题标题】:Is there an easy way to autowire empty collection if no beans present in Spring?如果 Spring 中没有 bean,是否有一种简单的方法可以自动装配空集合?
【发布时间】:2013-10-10 14:50:00
【问题描述】:

如果我有 @Autowired List<SomeBeanClass> beans; 并且没有 SomeBeanClass 的豆子,我会得到:

没有为依赖项 [SomeBeanClass 的集合] 找到类型为 [SomeBeanClass] 的匹配 bean:预计至少有 1 个 bean 有资格作为此依赖项的自动装配候选者。依赖注解:{@org.springframework.beans.factory.annotation.Autowired(required=true)}

如果我添加(required=false),我得到null 对应beans。但它看起来像需要空检查的容易出错的解决方案。

如果没有 bean,是否有一种简单的方法(一行)来自动装配空集合?

【问题讨论】:

    标签: java spring


    【解决方案1】:

    Spring 4 和 Java 8 有几个选项:

    @Autowired(required=false)
    private List<Foo> providers = new ArrayList<>();
    

    您也可以将java.util.Optional 与构造函数一起使用:

    @Autowired
    public MyClass(Optional<List<Foo>> opFoo) {
        this.foo = opFoo.orElseGet(ArrayList::new);
    }
    

    您还应该能够使用Optional&lt;List&lt;Foo&gt;&gt; opFoo; 自动连接一个字段,但我还没有使用过。

    【讨论】:

    • 谢谢!如果 bean 的列表是不可变的,最好使用 Collections.emptyList() 而不是 new ArrayList()。
    【解决方案2】:

    如果我添加(required=false),我会得到null for beans

    该字段是明确设置为 null 还是根本没有设置?尝试添加初始化表达式

    @Autowired(required=false) List<SomeBeanClass> beans = new ArrayList<>();
    

    【讨论】:

    • 这行不通。 Spring 仍然会抱怨它做不到。
    • 除非你输入required = false
    • @SotiriosDelimanolis 我指的是这种情况,抱歉,我没有说得很清楚。
    • 最好分配Collections.EMPTY_LIST(如果使用Guava,则分配ImmutableList.&lt;SomeBeanClass&gt;of())。
    • 如何通过构造函数注入来做到这一点?
    猜你喜欢
    • 2016-01-19
    • 2010-12-17
    • 1970-01-01
    • 2017-04-29
    • 2012-04-30
    • 2020-11-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多