如何通过ID注入Spring依赖项? [英] How do I inject a Spring dependency by ID?

查看:519
本文介绍了如何通过ID注入Spring依赖项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个具有相同类型(BeanType)的bean.如何通过带有注解的ID注入它们?说:

I have several beans with the same type (BeanType). How do I inject them by ID with an annotation? Say:

@Autowired @ID("bean1")
public void setBean( BeanType bean ) {
}

但是没有注释@ID.

我只找到了@Qualifier,这意味着我必须给我所有的bean IDs 限定词.当然,有更简单的方法吗?

I only found @Qualifier which would mean that I would have to give all my beans IDs and qualifiers. Surely, there is a more simple way?

推荐答案

最简单的解决方案是使用@Resource

Simplest solution is to use @Resource

@Resource(name="bean1")
public void setBean( BeanType bean ) {
}

偶然地,@Qualifier 用于通过ID引用与@Autowired一起使用的bean,例如

Incidentally, @Qualifier is used to refer to beans by ID for use with @Autowired, e.g

@Autowired @Qualifier("bean1")
public void setBean( BeanType bean ) {
}

其中,bean1是要注入的bean的ID.

where bean1 is the ID of the bean to be injected.

请参见 Spring手册:

对于后备匹配,bean名称被认为是默认的限定符值.因此,您可以使用id"main"而不是嵌套的qualifier元素定义bean,从而得到相同的匹配结果.但是,尽管您可以使用此约定按名称引用特定的bean,但@Autowired基本上是关于带有可选语义限定符的类型驱动的注入.这意味着,即使带有Bean名称后备的限定符值,在类型匹配集合中也始终具有狭窄的语义.他们没有在语义上表达对唯一bean id的引用.

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, @Autowired is 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.

如果您打算按名称表示注释驱动的注入,则即使技术上可以通过@Qualifier值引用bean名称,也不要主要使用@Autowired.而是使用JSR-250 @Resource批注,该批注的语义定义是通过其唯一名称来标识特定目标组件,而声明的类型与匹配过程无关.

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 @Qualifier values. Instead, use the JSR-250 @Resource annotation, which is semantically defined to identify a specific target component by its unique name, with the declared type being irrelevant for the matching process.

我更喜欢@Resource,它更干净(不是特定于Spring).

I prefer @Resource, it's cleaner (and not Spring-specific).

这篇关于如何通过ID注入Spring依赖项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆