通过使用Spring的构造函数自动装配的集合 [英] Autowiring a collection via the constructor with 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) {
// ...
}
}
这我尝试用下面的春天上下文中运行:
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" />
这无法与运行:
类型没有匹配的豆
[java.lang.String中]发现
依赖[收藏
java.lang.String中]:预计至少有1
豆这有资格作为自动装配
候选人这种依赖性。
注释依赖:
{@ org.springframework.beans.factory.annotation.Qualifier(值=栏)}
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
注释。一个自动装配收集方法提供了特定类型的所有豆。使用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.
[...]这是自己定义为一个集合或地图类型豆类无法通过 @Autowired
由于类型匹配是没有正确适用于他们注射。使用 @Resource
这样的豆子,用唯一的名称指的是特定集合/图豆。
[...] 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.
请参阅the Spring文档了解更多详细信息。
See the Spring documentation for more details.
这篇关于通过使用Spring的构造函数自动装配的集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!