如何通过 ID 注入 Spring 依赖项?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4648655/
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
How do I inject a Spring dependency by ID?
提问by Aaron Digulla
I have several beans with the same type (BeanType). How do I inject them by ID with an annotation? Say:
我有几个相同类型的豆子 ( BeanType)。如何通过带有注释的 ID 注入它们?说:
@Autowired @ID("bean1")
public void setBean( BeanType bean ) {
}
But there is no annotation @ID.
但是没有注释@ID。
I only found @Qualifierwhich would mean that I would have to give all my beans IDs andqualifiers. Surely, there is a more simple way?
我只发现@Qualifier这意味着我必须提供我所有的 bean ID和限定符。当然,还有更简单的方法吗?
回答by skaffman
Simplest solution is to use @Resource
最简单的解决方案是使用 @Resource
@Resource(name="bean1")
public void setBean( BeanType bean ) {
}
Incidentally, @Qualifierisused to refer to beans by ID for use with @Autowired, e.g
顺便说一下,@Qualifier在使用ID来指代豆用于在使用@Autowired,例如
@Autowired @Qualifier("bean1")
public void setBean( BeanType bean ) {
}
where bean1is the ID of the bean to be injected.
其中bean1要被注入的bean的ID。
See the Spring manual:
请参阅弹簧手册:
For a fallback match, the bean name is considered a default qualifier value. Thus you can define the bean with an id "main" instead of the nested qualifier element, leading to the same matching result. However, although you can use this convention to refer to specific beans by name,
@Autowiredis fundamentally about type-driven injection with optional semantic qualifiers. This means that qualifier values, even with the bean name fallback, always have narrowing semantics within the set of type matches; they do not semantically express a reference to a unique bean id.
对于回退匹配,bean 名称被视为默认限定符值。因此,您可以使用 id “main”而不是嵌套的限定符元素来定义 bean,从而得到相同的匹配结果。但是,尽管您可以使用此约定来按名称引用特定的 bean,但
@Autowired基本上是关于带有可选语义限定符的类型驱动注入。这意味着限定符值,即使有 bean 名称回退,在类型匹配集中总是具有缩小语义;它们没有在语义上表达对唯一 bean id 的引用。
and
和
If you intend to express annotation-driven injection by name, do not primarily use
@Autowired, even if is technically capable of referring to a bean name through@Qualifiervalues. Instead, use the JSR-250@Resourceannotation, which is semantically defined to identify a specific target component by its unique name, with the declared type being irrelevant for the matching process.
如果您打算按名称表示注解驱动的注入,请不要主要使用
@Autowired,即使技术上能够通过@Qualifier值引用 bean 名称。相反,使用 JSR-250@Resource注释,该注释在语义上定义为通过其唯一名称标识特定目标组件,声明的类型与匹配过程无关。
I prefer @Resource, it's cleaner (and not Spring-specific).
我更喜欢@Resource,它更干净(而不是特定于 Spring 的)。

