@Resource vs @Autowired vs @Inject
概述
在 spring 中 @Resource、@Autowired 和 @Inject 都可以用来注入 bean,那么他们有什么区别呢?
从最终结果来看
如果仅仅从结果来看,他们几乎没区别,只不过他们查找 Bean 的顺序不同。
@Autowired 和 @Inject 查找 Bean 的顺序
- 通过类型匹配 bean
- 应用 Qualifiers 限制
- 通过名称匹配
@Resource 查找 Bean 的顺序
- 通过名称匹配
- 通过类型匹配 bean
- 应用 Qualifiers 限制
注:@Autowired 使用 AutowiredAnnotationBeanPostProcessor 来注入 Bean,@Resource 使用 CommonAnnotationBeanPostProcessor 来注入 Bean。
从语义来看
stackoverflow 上对此作了比较好的回答:resource-vs-autowired
Both @Autowired (or @Inject) and @Resource work equally well. But there is a conceptual difference or a difference in the meaning:
@Resource means get me a known resource by name. The name is extracted from the name of the annotated setter or field, or it is taken from the name-Parameter.
@Inject or @Autowired try to wire in a suitable other component by type.
So, basically these are two quite distinct concepts. Unfortunately the Spring-Implementation of @Resource has a built-in fallback, which kicks in when resolution by-name fails. In this case, it falls back to the @Autowired-kind resolution by-type. While this fallback is convenient, IMHO it causes a lot of confusion, because people are unaware of the conceptual difference and tend to use @Resource for type-based autowiring.
意思是 @Resource 的本意是为了根据名称来匹配 Bean,但是不幸的是 spring 的实现却是先按照名称,如果按照名称找不到,则根据类型匹配;@Autowired 本意则是根据类型匹配。
温馨提示:反馈需要登录