java - Spring依赖注入(inject),使用@Named还是@Resource?

标签 java spring dependency-injection

在 Spring 中有两个单独的注解可以通过名称执行依赖注入(inject),javax.annotation.Resourcejavax.inject.Nameddocumentation at Spring指示 @Resource 应该用于按名称注入(inject):

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.

上面说的有点乱,Spring只提倡@Resource而不是@Autowired结合@Qualifer。在 later in the documentation 之前没有提到 @Named .

JSR-250 定义了 @Resource,而 JSR-330 定义了 @Inject@Named。我知道它们可以很容易地在 Spring 中混合搭配。使用哪个JSR?

似乎 Guice 和 CDI 的可移植性会很好,因此可以使用 JSR-330 注释。另一方面,文档还指出了一些 limitations在使用 JSR-330 注释时在 Spring 中。

注解按名称注入(inject)的最佳实践是什么(如果有的话)?

谢谢。

最佳答案

@Resource 较旧,从 Spring 2.5 开始支持,而 @Named 支持已在 Spring 3.0 中添加,它们都可以用于实现按名称注入(inject)的相同目的。

当使用 Spring 时,我对优先选择另一个的担忧是与 Spring 2.5 的向后兼容性以及是否可以在类路径上添加/假设 javax.inject。

关于java - Spring依赖注入(inject),使用@Named还是@Resource?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15071507/

相关文章:

java - Spring MVC Rest中处理JSon时如何处理POJO嵌套对象

java - 我的 log4j java.lang.ClassNotFoundException : =org. apache.log4j.RollingFileAppender 问题

java - 列出 Windows 文件类型

java - PipeLine释放资源lambda

java - 何时使用 Bean Validation 与自定义验证框架?

java - 绑定(bind)到多个主题的 Spring Cloud Stream Kafka 消费者

spring - Grails 4-Google Cloud Platform部署不断重启

.net-core - 尝试激活“GraphQL.Server.Internal.DefaultGraphQLExecuter”时无法解析类型 'xxxSchema' 的服务

java - 防止覆盖 guice 中已经绑定(bind)的类

php - 服务定位器、依赖注入(inject)(和容器)和控制反转