简体   繁体   English

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

[英]Spring — inject 2 beans of same type

I like constructor-based injection as it allows me to make injected fields final . 我喜欢基于构造函数的注入,因为它允许我final注入字段。 I also like annotation driven injection as it simplifies my context.xml . 我也喜欢注释驱动注入,因为它简化了我的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. 我可以用@Autowired标记我的构造函数,一切正常,只要我没有两个相同类型的参数。 For example, I have a class: 例如,我有一个班级:

@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. 应该有一种方法在类SomeClass的构造函数上指定bean ID,但我在文档中找不到它。 Is it possible, or am I dreaming of a solution that does not exist yet? 是可能,还是我梦想着一个不存在的解决方案呢?

@Autowired is by-type (in this case); @Autowired是按类型(在这种情况下); use @Qualifier to autowire by-name, following the example from spring docs : 使用@Qualifier按名称自动装配,遵循spring docs中的示例:

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. 注意:与@Autowired相比,它适用于字段,构造函数和多参数方法(允许在参数级别通过限定符注释缩小),@ Resource仅支持具有单个参数的字段和bean属性setter方法。 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) (在该文本下面是完整示例)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM