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

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

问题描述

我有几个相同类型的 bean (BeanType).如何通过带有注释的 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 引用 bean 以与 @Autowired 一起使用,例如

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"而不是嵌套的限定符元素来定义 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.

如果你打算通过名称来表达注解驱动的注入,不要主要使用 @Autowired,即使技术上能够通过 @Qualifier 引用一个 bean 名称值.相反,使用 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天全站免登陆