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?
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.
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, it causes a lot of confusion, because people are unaware of the conceptual difference and tend to use #Resource for type-based autowiring.
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.
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.
I would like to emphasize one comment from #Jules on this answer to this question. The comment brings a useful link: Spring Injection with #Resource, #Autowired and #Inject. I encourage you to read it entirely, however here is a quick summary of its usefulness:
How annotations select the right implementation?
#Autowired and #Inject
Matches by Type
Restricts by Qualifiers
Matches by Name
#Resource
Matches by Name
Matches by Type
Restricts by Qualifiers (ignored if match is found by name)
Which annotations (or combination of) should I use for injecting my beans?
Explicitly name your component [#Component("beanName")]
Use #Resource with the name attribute [#Resource(name="beanName")]
Why should I not use #Qualifier?
Avoid #Qualifier annotations unless you want to create a list of similar beans. For example you may want to mark a set of rules with a specific #Qualifier annotation. This approach makes it simple to inject a group of rule classes into a list that can be used for processing data.
Does bean injection slow my program?
Scan specific packages for components [context:component-scan base-package="com.sourceallies.person"]. While this will result in more component-scan configurations it reduces the chance that you’ll add unnecessary components to your Spring context.
Reference: Spring Injection with #Resource, #Autowired and #Inject
This is what I got from the Spring 3.0.x Reference Manual :-
Tip
If you intend to express annotation-driven injection by name, do
not primarily use #Autowired, even if is technically capable of
referring to a bean name through #Qualifier values. Instead, use the
JSR-250 #Resource annotation, which is semantically defined to
identify a specific target component by its unique name, with the
declared type being irrelevant for the matching process.
As a specific consequence of this semantic difference, beans that are
themselves defined as a collection or map type cannot be injected
through #Autowired, because type matching is not properly applicable
to them. Use #Resource for such beans, referring to the specific
collection or map bean by unique name.
#Autowired applies to fields, constructors, and multi-argument
methods, allowing for narrowing through qualifier annotations at the
parameter level. By contrast, #Resource is supported only for fields
and bean property setter methods with a single argument. As a
consequence, stick with qualifiers if your injection target is a
constructor or a multi-argument method.
#Autowired + #Qualifier will work only with spring DI, if you want to use some other DI in future #Resource is good option.
other difference which I found very significant is #Qualifier does not support dynamic bean wiring, as #Qualifier does not support placeholder, while #Resource does it very well.
For example:
if you have an interface with multiple implementations like this
interface parent {
}
#Service("actualService")
class ActualService implements parent{
}
#Service("stubbedService")
class SubbedService implements parent{
}
with #Autowired & #Qualifier you need to set specific child implementation
like
#Autowired
#Qualifier("actualService") or
#Qualifier("stubbedService")
Parent object;
which does not provide placeholder while with #Resource you can put placeholder and use property file to inject specific child implementation like
#Resource(name="${service.name}")
Parent object;
where service.name is set in property file as
#service.name=actualService
service.name=stubbedService
Hope that helps someone :)
Both of them are equally good. The advantage of using Resource is in future if you want to another DI framework other than spring, your code changes will be much simpler. Using Autowired your code is tightly coupled with springs DI.
When you analyze critically from the base classes of these two annotations.You will realize the following differences.
#Autowired uses AutowiredAnnotationBeanPostProcessor to inject dependencies.
#Resource uses CommonAnnotationBeanPostProcessor 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.
#Autowired / #Inject
1.Matches by Type
2.Restricts by Qualifiers
3.Matches by Name
#Resource
1.Matches by Name
2.Matches by Type
3.Restricts by Qualifiers (ignored if match is found by name)
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.
As a note here:
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext and SpringBeanAutowiringSupport.processInjectionBasedOnServletContext DOES NOT work with #Resource annotation. So, there are difference.
Related
I am working on a spring project that has the Service layer divided in two packages:
Interfaces
Implementation
While calling methods declared in the interface and defined in the implementation, which of the two should be #Autowired for which purpose?
What is the difference in autowiring the interface and the implementation?
I ask these keeping in mind that the point of this abstraction is usually to hide the declaration from the implementation
You can always autowire interfaces, but if you are having multiple implementations of your interface then you will need to tell spring which implementation to consider, and there are multiple ways to do so.
either mark one of them as #Primary
define name of bean on implementation and use #Qualifier annotation while autowiring it
As long as there is only a single implementation of the interface and that implementation is annotated with #Component with Spring's component scan enabled, Spring framework can find out the (interface, implementation) pair.
Once you have more than one implementation, then you need to qualify each of them and during auto-wiring, you would need to use the #Qualifier annotation to inject the right implementation, along with #Autowired annotation. If you are using #Resource (J2EE), then you should specify the bean name using the name attribute of this annotation.
Normally, both will work, you can autowire interfaces or classes.
So my question why did #javax.annotation.Resource worked but #AutoWired did not. For a test on a Restful controller, I was trying to inject MappingJackson2HttpMessageConverter with #Autowired, on start up the container failed to find a qualifying bean even though that class was on the path. Now, to solve this I went into a context xml file and added the bean:
<bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
Then in the test class had member variable:
#javax.annotation.Resource(name="jsonConverter")
private MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter;
Then spring finds the bean. Does Autowire only work for beans that were identified as beans by package scan?
Thanks ahead of time.
Autowired and Resource merely make the class types of annotated field, method or constructor eligible for dependency injection - it does not automatically add those types to the context of your Spring application!
So, as you suspect, in order for the annotations to work, you have to ensure that the auto-wired types are available in the application context yourself, e.g. with the Component annotation and package scan or by explicitly defining the bean in your application-context.xml as you did in your example.
In both cases Spring wires the dependency only when the bean getting wired is defined into spring context. You have to either define the bean in xml file or use annotation based bean definition to make it eligible for wiring.
On the other note, #Resource does name based wiring whereas #Autowire by default goes with type based.
Please see #Resource vs #Autowired for more context on topic.
This is from Spring reference. The second para may provide pointers.
If you intend to express annotation-driven injection by name, do not
primarily use #Autowired, even if is technically capable of referring
to a bean name through #Qualifier values. Instead, use the JSR-250
#Resource annotation, which is semantically defined to identify a
specific target component by its unique name, with the declared type
being irrelevant for the matching process.
As a specific consequence of this semantic difference, beans that are
themselves defined as a collection or map type cannot be injected
through #Autowired, because type matching is not properly applicable
to them. Use #Resource for such beans, referring to the specific
collection or map bean by unique name.
#Autowired applies to fields, constructors, and multi-argument
methods, allowing for narrowing through qualifier annotations at the
parameter level. By contrast, #Resource is supported only for fields
and bean property setter methods with a single argument. As a
consequence, stick with qualifiers if your injection target is a
constructor or a multi-argument method.
I think, in your case, there could be some issue with the default autowiring by name. So I guess Spring would be able to #Autowire the bean if you mention the qualifier. But then again if it is a case for #Resource, I think I'd prefer using it.
I would like to make sure if I understand this correctly. Spring needs a setter to inject a field reference? Couldn't it do it by just detecting it as a public field?
Is there an alternative to this. From what I understand Java EE's #Inject annotation can do this without any problem. But I have always been inclined more to Spring.
This depends on how you're creating your bean. Spring does not require setters. There are a number of other ways:
Autowiring (with or without Qualifiers) via annotation at the field level
Constructor injection (either by xml or annotations in the code)
Public fields (as you suggested) might work, though i have never tried it, and would advise against it even if it does.
Unfortunately, the XML approach does not look into private fields (that i know of). You either need to add a setter, use the constructor, or set up some sort of autowiring.
Keep in mind, autowiring can be combined with XML. Spring will pay attention to your wiring annotations even if you create your bean via xml (as opposed to something like #Component and component scanning).
It is not necessary to have Setter to inject a reference, you can use Autowire on a public variable of a class or on the setter method, u can also inject beans using constructor-arg which is a good way of injecting dependencies and autowiring can be done on Constructors also. #inject also does the same functionality as #autowired, however #Autowired has an additional behaviour where it internally also uses #required attribute, to see if the bean has a references and injected properly.
Spring provides several alternatives for DI besides setter injection. For example, you can use constructor injection. Alternatively, you can use Spring's #Autowired annotation for constructor, field or setter injection. Since you mentioned it, I guess that you would also be interested in knowing that Spring supports the #Inject annotation.
Injecting bean with scope prototype with #Autowired usually doesn't work as expected. But when writing code, it's easy to accidentally inject a prototype.
Is there a way to get a list of all #Autowired fields and methods and to match that with a Spring AppContext to check for this?
One approach could be to override org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor(which is responsible for processing #Autowired, #Inject, #Resource etc) and perform the checks that you have mentioned in this overridden bean post processor. However, AutowiredAnnotationBeanPostProcessor gets registered with quite a few of the common custom namespaces (context:component-scan, context:annotation-config etc), so these custom annotations will have to be replaced with the corresponding bean variation and the overridden post processor also registered as a bean.
In another question I asked, raised a concern that spring framework is not type safe. Is it true, or fixed, and can you give an example what it means exactly?
First of all, what does "type-safe" mean for a dependency injection framework. What I can think of is that you can get a bean from the context by specifying a type, and not just a bean name. Spring 3 allows this.
Otherwise, type-safety means that when you can define your dependencies by their type. And you can do this in all versions of spring.
Another thing is compile-time safety. With spring pre-3.0 when you had to differentiate between two beans that share the same interface (or supertype) by using their string-based name. In spring 3.0 you can use annotation-based qualifiers (using javax.inject.Qualifier), so it is compile-time safer as well.
Another thing to mention is the use of generics. You can have, for example #Inject List<MyService> in spring.
Define a custom annotation using #Qualifier
To identify the injected bean without specifying the name, we need to create a custom annotation. This is an equivalent procedure to the use of JSR 330 annotations(Inject) in CDI.
#Target({ElementType.Field, ElementType.Parameter})
#Retention(RetentionPolicy.RUNTIME)
#Qualifier
public #Interface Student {
}
Now assign this custom annotation to implementation of EntityDao Interface
#Component
#Student
public class StudentDao implements EntityDao {
}
#Component tells Spring that this a bean definition. #Student annotation is used by Spring IoC to identify StudentDao as EntityDao's implementation whenever reference of EntityDao is used.
Inject the bean using #Autowired and custom qualifier
Something like this.
#Autowired
#Student
private EntityDao studentDao; // So the spring injects the instance of StudentDao here.
This makes less use of String-names, which can be misspelled and are harder to maintain. - I find this post very useful.
http://www.coolcoder.in/2011/08/how-to-use-type-safe-dependency.html
It depends on how you use it and what you mean by type-safe (see Bozho's answer for more info on the latter): if you use the xml config to produce your beans, then you're probably type-safe after start-up.
However, if you use the new Java Bean config (which has its own limitations) you get compile-time safety.
I'm not advocating the latter over the former, but it's something to consider.