Java 如果 Spring 中没有 bean,是否有一种简单的方法来自动装配空集合?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19299114/
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
Is there an easy way to autowire empty collection if no beans present in Spring?
提问by Timofey Gorshkov
If I have @Autowired List<SomeBeanClass> beans;
and no beans of SomeBeanClass
, I get:
如果我有@Autowired List<SomeBeanClass> beans;
而没有豆类SomeBeanClass
,我会得到:
No matching bean of type [SomeBeanClass] found for dependency [collection of SomeBeanClass]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
没有为依赖项 [SomeBeanClass 的集合] 找到类型为 [SomeBeanClass] 的匹配 bean:预期至少有 1 个 bean 有资格作为此依赖项的自动装配候选者。依赖注解:{@org.springframework.beans.factory.annotation.Autowired(required=true)}
If I add (required=false)
, I get null
for beans
. But it looks like error prone solution requiring null checks.
如果我加入(required=false)
,我得到null
了beans
。但它看起来像需要空检查的容易出错的解决方案。
Is there an easy way (one liner) to autowire empty collection if no beans present?
如果没有豆类,是否有一种简单的方法(一个班轮)来自动装配空集合?
采纳答案by Ian Roberts
If I add
(required=false)
, I getnull
forbeans
.
如果我加入
(required=false)
,我得到null
了beans
。
Does the field get explicitly set to null or does it simply not get set at all? Try adding an initializer expression
该字段是明确设置为 null 还是根本没有设置?尝试添加初始化表达式
@Autowired List<SomeBeanClass> beans = new ArrayList<>();
回答by Benjamin M
There are a few options with Spring 4 and Java 8:
Spring 4 和 Java 8 有几个选项:
@Autowired(required=false)
private List<Foo> providers = new ArrayList<>();
You can also use java.util.Optional
with a constructor:
您还可以java.util.Optional
与构造函数一起使用:
@Autowired
public MyClass(Optional<List<Foo>> opFoo) {
this.foo = opFoo.orElseGet(ArrayList::new);
}
You should also be able to autowire an a field with Optional<List<Foo>> opFoo;
, but I haven't used that yet.
您还应该能够使用 自动装配 a 字段Optional<List<Foo>> opFoo;
,但我还没有使用过。