如果Spring中没有bean,是否有一种简单的方法可以自动装配空集合? [英] Is there an easy way to autowire empty collection if no beans present in Spring?

查看:124
本文介绍了如果Spring中没有bean,是否有一种简单的方法可以自动装配空集合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有 @Autowired List< SomeBeanClass> bean; 并且没有的Bean> SomeBeanClass ,我得到:

If I have @Autowired List<SomeBeanClass> beans; and no beans of SomeBeanClass, I get:


找不到[SomeBeanClass]类型的匹配bean,用于依赖[SomeBeanClass的集合]:期望至少有一个bean可以作为此依赖项的autowire候选者。依赖注释:{@ org.springframework.beans.factory.annotation.Autowired(required = true)}

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

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

If I add (required=false), I get null for beans. But it looks like error prone solution requiring null checks.

如果没有豆子存在,是否有一种简单的方法(一个班轮)自动装配空集合?

Is there an easy way (one liner) to autowire empty collection if no beans present?

推荐答案


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

该字段是否显式设置为null或者根本没有设置它?尝试添加初始化表达式

Does the field get explicitly set to null or does it simply not get set at all? Try adding an initializer expression

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

这篇关于如果Spring中没有bean,是否有一种简单的方法可以自动装配空集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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