在 Spring 中有两个单独的注解可以通过名称执行依赖注入(inject),javax.annotation.Resource
和 javax.inject.Named
。 documentation 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/