@Resource 与 @Autowired [英] @Resource vs @Autowired
问题描述
哪个注解,@Resource(jsr250) 或 @Autowired(特定于 Spring 的)我应该在 DI 中使用吗?
Which annotation, @Resource (jsr250) or @Autowired (Spring-specific) should I use in DI?
我过去都成功使用过,@Resource(name="blah")
和 @Autowired @Qualifier("blah")
I have successfully used both in the past, @Resource(name="blah")
and @Autowired @Qualifier("blah")
我的直觉是坚持使用 @Resource
标签,因为它已被 jsr 人员批准.
有人对此有强烈的想法吗?
My instinct is to stick with the @Resource
tag since it's been ratified by the jsr people.
Anyone has strong thoughts on this?
推荐答案
在 spring pre-3.0 中,选择哪一个并不重要.
In spring pre-3.0 it doesn't matter which one.
在 spring 3.0 中支持标准 (JSR-330) 注释 @javax.inject.Inject
- 使用它,结合 @Qualifier
.请注意,spring 现在还支持 @javax.inject.Qualifier
元注释:
In spring 3.0 there's support for the standard (JSR-330) annotation @javax.inject.Inject
- use it, with a combination of @Qualifier
. Note that spring now also supports the @javax.inject.Qualifier
meta-annotation:
@Qualifier
@Retention(RUNTIME)
public @interface YourQualifier {}
所以你可以拥有
<bean class="com.pkg.SomeBean">
<qualifier type="YourQualifier"/>
</bean>
或
@YourQualifier
@Component
public class SomeBean implements Foo { .. }
然后:
@Inject @YourQualifier private Foo foo;
这减少了字符串名称的使用,字符串名称可能会拼写错误并且更难维护.
This makes less use of String-names, which can be misspelled and are harder to maintain.
至于原问题:两者都没有指定注解的任何属性,按类型进行注入.区别在于:
As for the original question: both, without specifying any attributes of the annotation, perform injection by type. The difference is:
@Resource
允许你指定注入 bean 的名称@Autowired
允许您将其标记为非强制性.
@Resource
allows you to specify a name of the injected bean@Autowired
allows you to mark it as non-mandatory.
这篇关于@Resource 与 @Autowired的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!