Spring getter and setter dependent? - java

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.

Related

Do we have to write setter method to use #Inject annotation?

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.

When default constructor is required explicitly along with parameterized constructor

I am trying to learn spring dependency injection.
I want to know when there is need of default constructor in dependency injection
and what happen if we do not use default constructor explicitly
You have to provide a default constructor, if you plan on instantiating the bean without any arguments.
You should only provide a default constructor if there is a safe way to instantiate the bean that way - let the code document itself.
It is much better to include your bean's dependencies as constructor parameters, which allows you to make it very clear what your bean needs. The following is very clear:
#Autowired
public MyBean(WidgetService widgetService, NutService nutService, BoltService boltService) {
Whereas a default constructor for MyBean with the #Autowired annotation on various setters can get you into situations where the bean doesn't have all the dependencies it needs:
public MyBean() {
This is very useful when instantiating the bean manually, for example when testing the object.
Also, don't confuse the needs of Hibernate and other mapping solutions which tend to need a default constructor as well as a parameterised one, with other objects such as Spring Beans which don't. Mapping solutions tend to create an empty instance of the POJO (Plain Old Java Object) and then call setters to store values when unmarshalling from the database/XML/JSON/etc.

How exactly does Spring inject properties when annotating with #Value?

I've been wondering: how exactly does Spring inject properties when using the #Value annotation? What's the mechanism behind this that checks if a field has the annotation? Is it using reflection and some class that finds all annotated classes and creates an instance of them injecting the property, or is it doing it some other way? I know annotation processing would only be used during compilation and will not change the code, so what's happening behind the scenes here really...?
Thanks in advance!
The #Value annotation type has the #Retention(value=RUNTIME) annotation, which means that the information is available at runtime (i.e. using reflection).
A BeanPostProcessor, in particular the AutowiredAnnotationBeanPostProcessor can check for the presence of this annotation on fields, methods or constructors of a bean after instantiation.
If annotation-config feature is on then each time Spring instantiates a bean it goes thru all of its fields and methods and checks if they are annotated with one of Spring supported annotations using reflection.

is spring framework 3.0 type-safe

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.

#Resource vs #Autowired

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.

Categories