使用 Spring 通过构造函数自动装配集合 [英] Autowiring a collection via the constructor with Spring

查看:45
本文介绍了使用 Spring 通过构造函数自动装配集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个看似简单的问题,如标题所述.这是我的课程类型:

I have what seems to be a simple problem, as stated in the title. Here is the kind of class I have :

public class Foo {
    @Autowired
    public Foo(@Qualifier("bar") Set<String> bar) {
        // ...
    }
}

我尝试使用以下 spring 上下文运行:

Which I try to run with the following spring context :

<context:annotation-config />
<util:set id="bar">
    <value>tata</value>
    <value>titi</value>
    <value>toto</value>
</util:set>
<bean id="foo" class="Foo" />

这无法运行:

没有匹配的 bean 类型[java.lang.String] 找到了依赖 [集合的java.lang.String]:预计至少为 1符合自动装配条件的 bean这种依赖的候选者.依赖注解:{@org.springframework.beans.factory.annotation.Qualifier(value=bar)}

No matching bean of type [java.lang.String] found for dependency [collection of java.lang.String]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Qualifier(value=bar)}

请注意,如果我向构造函数添加其他参数,它会正常工作.如果我使用 setter 注入,它工作正常.我确定我错过了一些明显的东西......你知道吗?

Note that if I add other parameters to my constructor, it works fine. If I use setter injection, it works fine. I'm sure I miss something obvious ... do you know what ?

推荐答案

使用 @Autowired 注释无法自动装配集合.自动装配的集合意味着提供特定类型的所有 bean".使用 JSR-250 @Resource 注释,您可以声明您希望通过其名称而不是其类型注入资源.或者您显式注入依赖项.

Autowiring collections is not possible using the @Autowired annotation. An autowired collection means "to provide all beans of a particular type". Using the JSR-250 @Resource annotation, you can declare that you want a resource injected by its name, not its type. Or you inject the dependency explicitly.

[...] 本身定义为集合或映射类型的 bean 不能通过 @Autowired 注入,因为类型匹配不适用于它们.对此类 bean 使用 @Resource,通过唯一名称引用特定的集合/映射 bean.

[...] beans which are themselves defined as a collection or map type cannot be injected via @Autowired since type matching is not properly applicable to them. Use @Resource for such beans, referring to the specific collection/map bean by unique name.

请参阅 Spring 文档 了解更多详情.

See the Spring documentation for more details.

这篇关于使用 Spring 通过构造函数自动装配集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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