Java Spring -- 注入 2 个相同类型的 bean

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2153657/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 04:10:47  来源:igfitidea点击:

Spring -- inject 2 beans of same type

javaspring

提问by Guillaume

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 @Autowiredand everything works fine, as long as I don't have two parameters of the same type. For example, I have a class:

我喜欢基于构造函数的注入,因为它允许我创建注入的字段final。我也喜欢注释驱动的注入,因为它简化了我的context.xml. 我可以标记我的构造函数@Autowired并且一切正常,只要我没有两个相同类型的参数。例如,我有一个类:

@Component
public class SomeClass {
    @Autowired(required=true)
    public SomeClass(OtherClass bean1, OtherClass bean2) {
        …
    }
}

and an application context with:

以及具有以下内容的应用程序上下文:

<bean id="bean1" class="OtherClass" />
<bean id="bean2" class="OtherClass" />

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?

应该有一种方法可以在 class 的构造函数上指定 bean ID SomeClass,但是我在文档中找不到它。是否有可能,或者我是否梦想一个尚不存在的解决方案?

采纳答案by Bozho

@Autowiredis by-type (in this case); use @Qualifierto autowire by-name, following the example from spring docs:

@Autowired是按类型(在这种情况下);用于@Qualifier按名称自动装配,遵循spring 文档中的示例:

public SomeClass(
    @Qualifier("bean1") OtherClass bean1, 
    @Qualifier("bean2") OtherClass bean2) {
    ...
}

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.

注意:与适用于字段、构造函数和多参数方法(允许在参数级别通过限定符注释进行缩小)的 @Autowired 相比,@Resource 仅支持具有单个参数的字段和 bean 属性 setter 方法。因此,如果您的注入目标是构造函数或多参数方法,请坚持使用限定符。

(below that text is the full example)

(在该文本下方是完整示例)