@Resource VS @Autowired [英] @Resource vs @Autowired
问题描述
这批注, @Resource ( JSR250 )或 @Autowired (春具体)我应该使用使用DI什么时候?
Which annotation, @Resource (jsr250) or @Autowired (Spring specific) should I be using when using DI?
我已经成功地使用无论在过去, @资源(名称=嗒嗒)
和 @Autowired @Qualifier(嗒嗒)
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 have strong thoughts on this?
推荐答案
在春天pre-3.0不要紧哪一个。
In spring pre-3.0 it doesn't matter which one.
在春3.0有对标准的支持( JSR-330 )注释 @ javax.inject.Inject
- 使用它,用 @Qualifier
的组合。请注意,现在春天还支持 @ 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 VS @Autowired的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!