is it mandatory to write a setter function when we use #Inject annotation
Nope. It is not mandatory. Reflection is used to set the value.
See this and this for more info.
No, we don,t have to write the setter method for #Inject, it is same annotation as the #Autowired.
#Inject is part of a Java technology called CDI that defines a standard for dependency injection similar to Spring. In a Spring application, the two annotations works the same way as Spring has decided to support some JSR-299 annotations in addition to their own.
#Inject can be injected the reference to the implementation of the Provider interface, which allows injecting the deferred references.
Is there anyway to specify order in which beans to be instantiated? i.e. I want specific beans to be instantiated before other beans, its like startup sequence.
I am using Spring 3.2 and annotation based declaration method.
If bean A depends on bean B by defining <property/>, #Autowired or <constructor-arg/> then the order is forced and fixed by the Spring container. No problem here.
But if you want to enforce specific order of bean creation which is not expressed via explicit dependencies feel free to use:
<bean id="A" depends-on="B"/>
<bean id="B"/>
or better (with annotations, works also with #Bean Java configuration):
#Service
#DependsOn("B")
public class A {}
or even better... don't use it. These constructs are a code smell and often suggest you have some nasty invisible dependency between your components.
Agreed with the answer provided by Tomasz. If you know that bean A depends on bean B then this is right approach.
Sometimes you have logic that should be executed before all beans instantiation. In this case you can use BeanFactoryPostProcessor. Spring creates and executes BeanFactoryPostProcessors first and after that only all other beans. At the same time if your BeanFactoryPostProcessor depends on some bean A you can use property or constructor injection. In this case Spring will create bean A first, then your BeanFactoryPostProcessor, call BeanFactoryPostProcessor and after that only instatiate all other beans in the context.
You can use the Ordered interface on your bean to define ordering relative to other beans.
Further,if you use BeanFactoryPostProcessor as emamedov said, Ordered interface can be implemented to control BeanFactoryPostProcessor instance sequence.
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.
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.
I am trying to let a piece of runtime state decide WHICH implementation of an interface to use, preferably solely by autowiring.
I have tried making an object factory for the interface thet uses dynamic proxies, and I used qualifiers to coerce the #Autowired injections to use the factory. The qualifiers are necessary because both the factory and the implementations respond to the same interface.
The problem with this is that I end up annotating every #Autowired reference with the #Qualifier. What I'd really want to do is annotate the non-factory implementations with something like #NotCandidateForAutowiringByInterface (my fantasy annotation), or even better make spring prefer the single un-qualified bean when injecting to an un-qualified field
I may thinking along the totally wrong lines here, so alternate suggestions are welcome.
Anyone know how to make this happen ?
You could use #Resource and specify the bean name of the factory.
I haven't looked at this myself but I noticed Spring JavaConfig is made it to M4 and it seems to allow more flexible configuration through a combination of annotations and Java code. I wonder if it would offer a solution to your problem.