Spring - 注入2个相同类型的bean [英] Spring -- inject 2 beans of same type
问题描述
我喜欢基于构造函数的注入,因为它允许我创建注入的字段 final
。我也喜欢注释驱动注入,因为它简化了我的 context.xml
。我可以用 @Autowired
标记我的构造函数,一切正常,只要我没有两个相同类型的参数。例如,我有一个类:
I like constructor-based injection as it allows me to make injected fields final
. I also like annotation driven injection as it simplifies my context.xml
. I can mark my constructor with @Autowired
and everything works fine, as long as I don't have two parameters of the same type. For example, I have a class:
@Component
public class SomeClass {
@Autowired(required=true)
public SomeClass(OtherClass bean1, OtherClass bean2) {
…
}
}
和应用程序上下文:
<bean id="bean1" class="OtherClass" />
<bean id="bean2" class="OtherClass" />
应该有一种方法在类 SomeClass
,但我在文档中找不到它。是否有可能,或者我是否仍在梦想一个尚不存在的解决方案?
There should be a way to specify the bean ID on the constructor of the class SomeClass
, but I can't find it in the documentation. Is it possible, or am I dreaming of a solution that does not exist yet?
推荐答案
@Autowired
是by-type(在这种情况下);按照示例 @Qualifier 按名称自动装配beans.htmlrel =noreferrer>来自spring docs :
@Autowired
is by-type (in this case); use @Qualifier
to autowire by-name, following the example from spring docs:
public SomeClass(
@Qualifier("bean1") OtherClass bean1,
@Qualifier("bean2") OtherClass bean2) {
...
}
注意:与@Autowired相比,它适用于字段,构造函数和多参数方法(允许缩小通过限定符注释)参数级别),仅对具有单个参数的字段和bean属性setter方法支持@Resource。因此,如果您的注入目标是构造函数或多参数方法,请坚持使用限定符。
Note: In contrast to @Autowired which is applicable to fields, constructors and multi-argument methods (allowing for narrowing through qualifier annotations at the parameter level), @Resource is only supported for fields and bean property setter methods with a single argument. As a consequence, stick with qualifiers if your injection target is a constructor or a multi-argument method.
(在该文本下面是完整示例)
(below that text is the full example)
这篇关于Spring - 注入2个相同类型的bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!