when to go for constructor injection and when to go for parameter injection in Spring - spring

I'm a fresher, I'm recently started learning Spring.In spring dependency injection,we
can inject a bean in 2 ways,one is through constructor and the other one is through
setter method.My question is, for what situations constructor injection is better and
for what situations setter method injection is better. my focus only on where to use?
Give me an example if possible... waiting for your valuable reply..

There is a third way: Field injection.
You can directly apply the Annotation #Resource, #Inject or #Autowire at a (even private) field. This field even does not need to hava a getter or setter.
If you are building a Spring application, and there is no plan to use the classes in a not Spring application or a library, then the field injection is enough for 90% of the classes.
I prefer it, because it is less code.
Of course if you use a constructor for mandatory references then there is no way to forget one of them when creating a new instance. But (and this is my point of view, that differs from Alef Arendsen in his 3 year old Spring 2.0 blog entry "Setter injection versus constructor injection and the use of #Required") you have a spring bean and not a simple class. And this bean is created by spring, not directly by you. So if you use #Resource, #Inject or #Autowire for fields or setter spring checks them too and do not put the bean and the whole application in service if not all references can be satisfied.

I'd say go for constructor injection.
In some cases go for setter injection if dependency is optional.
If you forced to use setter injection and use Spring, the use #Required to ask Spring to enforce it.
Apply common sense in all cases :)

Related

Spring managed vs non-managed beans

I have a simple Result data holder object that gets returned from a method.
I'm confused on what the right way of using or creating this object using Spring boot.
Should this class be marked with #Component annotation?
Can I just create this object using 'new Result()' or should I autowire and use it?
If I use 'new Result()' then this instance will not be managed by Spring. Is that understanding correct? What are the advantages or disadvantages of managed vs non-managed beans.
Thanks,
Sudha
If I use 'new Result()' then this instance will not be managed by Spring. Is that understanding correct? What are the advantages or disadvantages of managed vs non-managed beans.
Well the greatest difference is the Inversion Of Control IoC (aka Dependency Injection DI). If Result is managed by spring, you can autowire other spring beans (like services, components, repositories and so on) Moreover you can autowire the Result bean in other spring beans. More details can be found here
Can I just create this object using 'new Result()' or should I autowire and use it?
Well it depends on your scenario. For example if you have a JSON response in a Spring controller, well in this case it's better to use a classic POJO and create it because it depends on your business logic.
On the other side id your bean is a kind of service who can be used in other points of your project because it offers some methods, well in this case I guess it's good to autowire it and make it as a spring bean
Should this class be marked with #Component annotation?
Well as I said earlier it depends on your scenario. In the case you described (result of a method) maybe it's better to use a classical POJO. But you didn't provide enough information

difference between dependency injection and autowiring

Can I know what is the difference between dependency injection and autowiring? Whether autowiring is different from dependency injection?
Which is the best way to autowiring(XML based or annotation based)?
Short answer: Dependency Injection is a design pattern, and #autowired is a mechanism for implementing it.
The DI idea is that, instead of your object creating an object it needs (say by using new to instantiate it), this needed object - a dependency - is handed to your object, typically using the constructor or a setter method. If you autowire, you're injecting a dependancy. In this case, Spring uses reflection to make this work, so you're not using the constructor or a setter method, but you're still injecting the dependency.
To answer question 2, its your choice. Personally, I find the XML configuration files cumbersome and use annotations whenever I can. You can accomplish whatever configuration you need to do either way.

Getting Spring object instantiation right

I'm new to Spring and a little confused about how it works. I get that I can use the application context to instantiate beans and have them populated. However, is the idea that I should be able to just write Bean b = new Bean() and then have Spring to somehow automagically populate that Bean?
I'm experimenting with Spring in a web application, and as far as I can see I need to inject the ApplicationContext into, say, the servlets to be able to instantiate other beans (services, daos etc.) from there. It's a bit cumbersome, but probably works.
However, is Spring meant to be able to hook into any object instantiation which happens on classes defined as beans in applicationContext.xml?
Spring is an Inversion of Control container. A bean is an object whose life cycle is managed by Spring. If you want Spring to populate an object, it needs to go through Spring, ie. it needs to be bean.
is Spring meant to be able to hook into any object instantiation
which happens on classes defined as beans in applicationContext.xml?
Spring doesn't hook into anything. You configure your beans and the relationships between them with Spring and Spring handles creating the instances and linking them up.
For domain objects, Spring provides a solution via the #Configurable annotation: http://docs.spring.io/spring/docs/4.0.0.RELEASE/spring-framework-reference/htmlsingle/#aop-atconfigurable
It requires compile- or load-time-weaving and, thus, introduces some additional complexity but having the convenience of using the standard new Bean() syntax plus Spring's autowiring is worth it in my opinion.
Alternatively, you could define your domain objects as beans with prototype scope and use some factory to create them using the Spring ApplicationContext.getBean() method. With a scope of prototype a new instance will be returned every time and since you go through the ApplicationContext, Spring will do all the dependency injection magic as usual.
As for services and other beans with singleton scope, you would typically NOT retrieve them by first injecting the ApplicationContext and using it but instead you would inject them via either a constructor, setter or annotation-based strategy. The documentation covers that in detail: http://docs.spring.io/spring/docs/4.0.0.RELEASE/spring-framework-reference/htmlsingle/#beans-factory-collaborators

Spring setter dependency injection after all beans have been created

I have a set of Spring beans created using constructor injection. Since there are (by design) circular references to other beans, I'd like to post-process the beans once they are all created to inject the references to other beans.
Initial attempts at using BeanPostProcessor show that the BeanPostProcessor is running after EACH bean is instantiated, not waiting until all have been instantiated.
Does Spring provide a mechanism for post-processing as set of beans after all have been created?
If you're creating the beans in an ApplicationContext, the ApplicationContext fires ApplicationEvents to any registered ApplicationListener callbacks. One of those should tell you when all the beans in the context are wired together via Spring.
Here's what the documentation says about circular dependencies:
If you use predominantly constructor injection, it is possible to
create an unresolvable circular dependency scenario.
For example: Class A requires an instance of class B through
constructor injection, and class B requires an instance of class A
through constructor injection. If you configure beans for classes A
and B to be injected into each other, the Spring IoC container detects
this circular reference at runtime, and throws a
BeanCurrentlyInCreationException.
One possible solution is to edit the source code of some classes to be
configured by setters rather than constructors. Alternatively, avoid
constructor injection and use setter injection only. In other words,
although it is not recommended, you can configure circular
dependencies with setter injection.
Unlike the typical case (with no circular dependencies), a circular
dependency between bean A and bean B forces one of the beans to be
injected into the other prior to being fully initialized itself (a
classic chicken/egg scenario).
I would just use setter injection in this case, or try to avoid the circular dependency in the first place. Another solution is to make one of the beans BeanFactoryAware, and to lookup the other bean from the bean factory when the reference is needed.

Using Spring to wire directly a concrete class

Does it makes sense in Spring to use #Autowired to wire directly to a concrete class and not to an interface (and make use of 'by type' autowiring)
If a class doesn't implements an interface wouldn't it be better to instantiate it via constructor or a factory (keeping things simple); rather than make it a Spring bean just for the heck of it.
Does it makes sense in Spring to use #Autowired to wire directly to a concrete class and not to an interface
Sure. The practice of autowiring is independent of what you're autowiring. It'll work with classes just as well as interfaces.
However, whether or not it's a good idea is debatable, although this is a more general question of whether you should always introduce an interface for a given class, rather than talk directly to the class type. The benefits include easier unit-testing and a cleaner design, at the expense of code clutter.
There's another good reason to autowire interface types rather than class types, which is that if Spring needs to generate a proxy object around the bean before injecting it, then if the bean's class defines any interfaces, then the proxy will implement those interfaces, and will not be type-compatible with the bean class itself. If you then try and autowire that bean by class type, it will fail. The easiest way to avoid this annoying scenario is to always autowire by interface type, that way it will lways work as you expect.
and make use of 'by type' autowiring
If you mean container-level byType autowiring, then you don't want to do that. It's the old Spring 1.x style of autowiring, and it's highly inflexibile (see limitations of autowiring).
Stick with #Autowired, it's much more flexible and easier to control.
If a class doesn't implements an interface wouldn't it be better to instantiate it via constructor or a factory (keeping things simple); rather than make it a Spring bean just for the heck of it.
The two questions are completely separate. An object should be made a Spring bean if you need Spring to control its dependencies and lifecycle, regardless of whether or not it implements interfaces. If you find that the object has no dependencies, and no meaningful interface, then perhaps there is no reason to make it a bean.
You will have to decide if hardwiring this dependency into other classes is ok. For instance, how many different classes are likely to require this dependency? If the answer is many then you will be creating many instances of this class where only one is required.
Also, what dependancies does this concrete class have? You will have to configure those inside the class that depends on it.
The object of dependency injection is to reduce the dependencies between classes and make your code loosely coupled.

Resources