哪个注释,@Resource (jsr250)或@Autowired (spring特定)我应该在DI中使用?

我已经成功地使用在过去,@资源(名称="blah")和@Autowired @Qualifier("blah")

我的直觉是坚持使用@Resource标签,因为它已经被jsr的人批准了。 有人对此有强烈的想法吗?


当前回答

使用@Resource,您可以进行bean自我注入,可能需要它来运行bean后处理器添加的所有额外逻辑,如事务或安全相关的东西。

Spring 4.3+ @Autowired也能做到这一点。

其他回答

这是我从Spring 3.0中得到的。x参考手册:-

Tip 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. As a specific consequence of this semantic difference, beans that are themselves defined as a collection or map type cannot be injected through @Autowired, because type matching is not properly applicable to them. Use @Resource for such beans, referring to the specific collection or map bean by unique name. @Autowired applies to fields, constructors, and multi-argument methods, allowing for narrowing through qualifier annotations at the parameter level. By contrast, @Resource is supported only for fields and bean property setter methods with a single argument. As a consequence, stick with qualifiers if your injection target is a constructor or a multi-argument method.

这里有一个注释: SpringBeanAutowiringSupport。processInjectionBasedOnCurrentContext和SpringBeanAutowiringSupport。processInjectionBasedOnServletContext不能使用@Resource注释。所以,这是有区别的。

当您从这两个注释的基类进行严格分析时。您将认识到以下不同之处。

@Autowired使用AutowiredAnnotationBeanPostProcessor注入依赖项。 @Resource使用CommonAnnotationBeanPostProcessor注入依赖项。

尽管它们使用不同的后置处理器类,但它们的行为几乎相同。 关键的区别在于它们的执行路径,我在下面强调了这一点。

@Autowired / @Inject

1.按类型匹配 2.限定词限制 3.名称匹配

@Resource

1.名称匹配 2.按类型匹配 3.通过限定符进行限制(如果通过名称找到匹配则忽略)

他们两个都一样好。使用Resource的优势在于,如果将来您想使用spring以外的另一个DI框架,您的代码更改将会简单得多。使用Autowired您的代码与spring DI紧密耦合。

主要的区别是,@Autowired是一个spring注释。而@Resource是由JSR-250指定的,正如您自己指出的那样。因此,后者是Java的一部分,而前者是Spring特有的。

因此,在某种意义上,你的建议是正确的。我发现人们使用@Autowired和@Qualifier,因为它更强大。从一个框架转移到另一个框架被认为是不太可能的,特别是在Spring的情况下。