Spring setter injection and constructor injection - spring

Kindly let help to understand in which scenario I should user constructor injection and setter injection. Please help me with appropriate Example.
Thanks in advance.

We usually advise people to use constructor injection for all
mandatory collaborators and setter injection for all other properties.
Again, constructor injection ensures all mandatory properties have
been satisfied, and it is simply not possible to instantiate an object
in an invalid state (not having passed its collaborators). In other
words, when using constructor injection you do not have to use a
dedicated mechanism to ensure required properties are set (other than
normal Java mechanisms).
More details http://blog.springsource.org/2007/07/11/setter-injection-versus-constructor-injection-and-the-use-of-required/

Personally, I tend towards constructor injection, and I do it for one primary reason.
Immutability.
With immutable objects, it is easier to make code thread safe. This is especially important when dealing with Spring singleton scope objects. If they are mutable, and accessed in different threads, it is not safe to change any of the shared state.
There are other reasons that immutability is beneficial, but I will let a webpage go on about that.

Related

can anyone please tell me what is the difference between Inversion of Control (IOC) and Dependency Injection (DI) in spring?

I'am seriously figuring out this for the last one week and continuously keep on reading articles and blogs so that I can understand the difference in the very leman language and terms so that I can understand easily!!!!!
Dependency injection is simply about depending on an abstract interface and passing a concrete implementation of that interface to your class through the constructor or a setter method. This allows you to use a different concrete implementation without changing your class. This is useful, for instance for testing.
IoC is also known as the Hollywood principle: don't call us, we call you. In this case a framework defines an interface and the application provides the concrete implementation. This helps to limit dependencies between classes. IoC is often implemented using dependency injection, but it's not a hard requirement.

How to specify object instantiation order in guice?

I'm creating two objects in two Guice modules, Object1 and Object2. Both these objects use Object3. How can I control the order in which Guice instantiates Object1 and Object2 (Object 1 before 2) as the state of Object3 set by Object1 is required for Object2 ? In spring this is similar to having a #DependsOn. But I couldn't find anything similar in Guice.
GuiceModule1
Object1(Object3)
GuiceModule2
Object2(Object3)
A way that I think could solve this is by passing Object2 as a parameter when constructing Object1, but that doesn't sound the right way as I have to do this just to define dependency creation order.
You can't enforce injection order in Guice via some annotation or built-in mechanism.
But you can trick Guice to enforce injection order by means of requiring class Object2 to hold a reference to Object1 without doing anything with the reference. It's definitely not clean but gets the job done easily.
Hint for dependency injection best practices
If it's possible you should restructure your class design in a way that injection order doesn't matter. The dependency order should be the only driver of injection order and this is where Guice or other DI frameworks excel.
Perhaps that's the reason why Guice doesn't provide such a built-in mechanism to enforce injection order as it comes with some other cost such as maintenance of the annotation and even some contradiction if your references change drastically so that the annotation would be the opposite of what your depdency graph says. I think you see where I'm heading to.
Without more information about your app it's difficult to give advice about how to do it "better".
Anyway I hope it helped!

Field injection with the benefits of constructor injection?

so I was reading about constructor injection vs field injection and the obvious points in favor of constructor injection is NPE avoiding and better testability, so my question is:
Spring won't allow you to start an application with a missing bean even if it's a field injected one, so no way to get a NPE. And as far as testability goes, you can just mock/spy the beans you want in your tests and it will work as well, so apart from convention is there a real benefit?
Spring won't allow you to start an application with a missing bean even if it's a field injected one
This is not always true, you might mark your beans as being lazy instantiated, so in this case it is quite possible that you will get the NPE, because injection will happen at the point bean is requested(used).
One of the advantages of constructor injection is that it is required injection, as opposite to field. So it is more error-prone.

Is IOC design pattern is independent of Factory design pattern?

I read somewhere, IOC is different from factory pattern. As Factory design pattern is more intrusive, where as Dependency Injection is not.
Could someone elaborate more on this?
Yes, IoC and Factory are two different things. IoC is actually a more generic term, and many things qualify as IoC, so it helps to further refine what it is you are referring to. For example, technically, any callback or event is considered an implementation of IoC. Most people mean Dependency Injection when they talk about IoC, however.
You can use a Factory to achieve Inversion of Control, just like you can use Dependency Injection to achieve it.
What you're probably thinking of is an Dependency Injection container, like Unity, Windows, or Ninject. A DI container is sort of a glorified abstract generic factory, but it does a lot more than that, including object lifetime management, conditional binding, etc...
It's important to separate the pattern (IoC or DI) from the implementations (Factory, DI Container, Poor mans DI, etc..) even though the implementations may themselves also be patterns.
Inversion of control containers is not primarily used for dependency injection. It's to let the container control the lifetime of your objects. Hence the inversion of control.
That's why you always specify a lifetime when you register things in the container (or just use the default lifetime)
However, since the container creates the objects for you, it can also provide dependency injection as an extra feature. So it's really a bonus.
Factory pattern on the other hand should ALWAYS create a new object. The purpose of factory pattern is simply to create the correct implementation for you.

Setter DI vs. Constructor DI in Spring?

Spring has two two types of DI: setter DI and construction DI.
Constructor-based DI fixes the order in which the dependencies need to be injected. Setter based DI does not offer this.
Setter-based DI helps us to inject the dependency only when it is required, as opposed to requiring it at construction time.
I do not see any other significant differences, as both types of Spring DI provide the same features - both setter and constructor DI inject the dependency when the code starts up. Granted, constructor DI will do it through the constructor while setter DI will do it through a setter right after constructing the object, but it does not make any difference for the developer in terms of performance, etc. Both also offer means to specify the order of dependency injection as well.
I'm looking for a scenario where one provides a distinct advantage over the other or where one type is completely unusable.
When it comes to Spring specific pros and cons:
Constructor injection (from the definition) does not allow you to create circular dependencies between beans. This limitation is actually an advantage of constructor injection - Spring can resolve circular dependencies when setter injection is used without you even noticing.
On the other hand if you use constructor injection CGLIB is not able to create a proxy, forcing you to either use interface-based proxies or a dummy no-arg constructor. See: SPR-3150
You should be deciding based on design considerations, not tool (Spring) considerations. Unfortunately, Spring has trained us to use setter injection because when it was originally conceived, there was no such thing as an "annotation" in Java, and in XML, setter injection works and looks much better. Today, we're freed from those constraints, thus allowing it to be a design decision again. Your beans should use constructor injection for any dependencies that are required by the bean and setter injection for dependencies that are optional and have a reasonable default, more or less as OOD has been telling us from the beginning.
Constructor Injection: We are injecting the dependencies through Constructor.
Generally we can use for Mandatory dependencies.
If you use the Constructor injection there is one disadvantage called "Circular Dependency".
Circular Dependency: Assume A and B. A is dependent on B. B is dependent on A. In this constructor injection will be failed. At that time Setter injection is useful.
If Object state is not inconsistent it won't create Object.
Setter Injection: We are injecting the dependencies through Setter methods.
This is useful for Non-Mandatory dependencies.
It is possible to re injecting dependencies by using Setter Injection. It is not possible in Constructor injection.
As per the content from spring.io from Spring 5 onwards
Since you can mix constructor-based and setter-based DI, it is a good rule of thumb to use constructors for mandatory dependencies and setter methods or configuration methods for optional dependencies. Note that use of the #Required annotation on a setter method can be used to make the property a required dependency.
The Spring team generally advocates constructor injection as it enables one to implement application components as immutable objects and to ensure that required dependencies are not null. Furthermore constructor-injected components are always returned to client (calling) code in a fully initialized state. As a side note, a large number of constructor arguments is a bad code smell, implying that the class likely has too many responsibilities and should be refactored to better address proper separation of concerns.
Setter injection should primarily only be used for optional dependencies that can be assigned reasonable default values within the class. Otherwise, not-null checks must be performed everywhere the code uses the dependency. One benefit of setter injection is that setter methods make objects of that class amenable to reconfiguration or re-injection later. Management through JMX MBeans is therefore a compelling use case for setter injection.
Here is the link for above quote
But, all of the injections types are available and none of them are deprecated. At a high-level you get the same functionality across all injection types.
In short, choose the injection type that works best for your team and project.
Recommendations from the Spring team and independent blog posts will vary over time. There is no hard-fast rule.
If a particular injection style was not recommended by the Spring team, then they would mark it as deprecated or obsolete. That is not the case with any of the injection styles.
Prefer setter injection.
Think what would be without spring (as Ryan noted). Would you pass the dependencies in constructor? If there are too many dependencies this seems wrong. On the other hand the constructor may be used to enforce the valid state of the object - require all dependencies and verify if they are non-null.
Proxies are another thing (As Tomasz noted) - you will need a dummy constructor which defeats the whole idea.
There is a 3rd option btw - field injection. I tend to be using that, although it is not such a good design decision, because it saves an extra setter, but if this is used outside of spring I will have to add the setter.
My 2 cents.
Assume a classA with 10 fields, with few injected dependencies.
Now if you need entire classA with all fields then you can go for constructor injection.
But if you need only one of the injected field to use in that class you can use setter injection.
This way,
You will not create new object each time.
You do not need to worry about circular dependency issue(BeanCurrentlyInCreationException).
You will not have to create other fields for class A so you have much more flexible code
Since you can mix both, Constructor DI- and Setter-based DI, it is a good rule of thumb to use constructor arguments for mandatory dependencies and setters for optional dependencies.
Note that the use of a #Required annotation on a setter can be used to make setters required dependencies.
Probably it's not main advantage. But let me explain mechanism of injection in Spring.
The meaning of the difference these two approaches is that with the way of injection using #Inject, #Autowire and so on, Spring will inject one bean into another using reflection, and with the way of the constructor, we ourselves use the constructor in order to initialize one bean by another bean without using reflection.
Therefore, the way with constructor better other option, at least that we don't use reflection-mechanism because reflection is an expensive operation from the machine-side.
P.S. Please consider, that correct use of construction DI it's when you manually create bean through constructor with params, even though you can you create using constructor without any of them.
no, even Constructor Injection happen , injection is still working, but just limited initialize , setter injection is optional and flexible. but it may generally for the parameter class , a spring bean with other spring beans

Resources