@Resource vs @Autowired [英] @Resource vs @Autowired
问题描述
哪个注释 @Resource ( jsr250 )或 @Autowired (Spring特定)应该在使用DI时使用?
我已经成功地使用了两者, @Resource(name =blah)
和 @Autowired @Qualifier(blah)
我的直觉是坚持使用 @Resource
标签,因为它已被jsr人批准。任何人都有强烈的想法?
在春季前3.0中,哪一个不重要。
在春季3.0中,支持标准( JSR-330 )注释 @ javax.inject.Inject
- 使用它,结合 @Qualifier
。请注意,spring现在还支持 @ javax.inject.Qualifier
元注释:
@Qualifier
@Retention(RUNTIME)
public @interface YourQualifier {}
所以你可以有
< bean class =com.pkg.SomeBean>
< qualifier type =YourQualifier/>
< / bean>
或
@YourQualifier
@Component
public class SomeBean实现Foo {..}
然后:
@Inject @YourQualifier private Foo foo;
这样可以减少使用字符串名称,这可能是拼写错误的,难以维护。 p>
对于原始问题:两者,没有指定注释的任何属性,请按类型执行注入。区别在于:
-
@Resource
允许您指定注入的名称bean -
@Autowired
允许您将其标记为非强制性。
Which annotation, @Resource (jsr250) or @Autowired (Spring specific) should I be using when using DI?
I have successfully used both in the past, @Resource(name="blah")
and @Autowired @Qualifier("blah")
My instinct is to stick with the @Resource
tag since it's been ratified by the jsr people. Anyone have strong thoughts on this?
In spring pre-3.0 it doesn't matter which one.
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 {}
So you can have
<bean class="com.pkg.SomeBean">
<qualifier type="YourQualifier"/>
</bean>
or
@YourQualifier
@Component
public class SomeBean implements Foo { .. }
And then:
@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
allows you to specify a name of the injected bean@Autowired
allows you to mark it as non-mandatory.
这篇关于@Resource vs @Autowired的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!