Which annotation, @Resource (jsr250) or @Autowired (Spring-specific) should I use in 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 has strong thoughts on this?
The primary difference is,
@Autowired
is a spring annotation. Whereas@Resource
is specified by the JSR-250, as you pointed out yourself. So the latter is part of Java whereas the former is Spring specific.Hence, you are right in suggesting that, in a sense. I found folks use
@Autowired
with@Qualifier
because it is more powerful. Moving from some framework to some other is considered very unlikely, if not myth, especially in the case of Spring.This is what I got from the Spring 3.0.x Reference Manual :-
With
@Resource
you can do bean self-injection, it might be needed in order to run all extra logic added by bean post processors like transactional or security related stuff.With Spring 4.3+
@Autowired
is also capable of doing this.@Resource
is often used by high-level objects, defined via JNDI.@Autowired
or@Inject
will be used by more common beans.As far as I know, it's not a specification, nor even a convention. It's more the logical way standard code will use these annotations.
When you analyze critically from the base classes of these two annotations.You will realize the following differences.
@Autowired
usesAutowiredAnnotationBeanPostProcessor
to inject dependencies.@Resource
usesCommonAnnotationBeanPostProcessor
to inject dependencies.Even though they use different post processor classes they all behave nearly identically. The differences critically lie in their execution paths, which I have highlighted below.
1.Matches by Type
2.Restricts by Qualifiers
3.Matches by Name
1.Matches by Name
2.Matches by Type
3.Restricts by Qualifiers (ignored if match is found by name)