35

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.

mskfisher
  • 3,291
  • 4
  • 35
  • 48
M Sach
  • 33,416
  • 76
  • 221
  • 314

9 Answers9

38

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

Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
  • Thanks Tomasz.Point1:- Does spring give runtime error in case of circular dependency? Point2:-Just trying to understand with example.Are you saying that if i have class A which is using Class B as dependency in its constructor(class B does not implement interface).Wont it be possible? – M Sach Oct 16 '11 at 05:53
  • 6
    Think about it: if bean A requires an instance of bean B on startup and bean B requires an instance of bean A, there is no way to instantiate them. When Spring detects such a situation it throws an exception when starting. However with setter/field injection Spring can firdt create instances and then inject them, no problem in this situation. – Tomasz Nurkiewicz Oct 16 '11 at 08:20
  • 3
    If this is a common problem in your project, though, then you probably have other things to worry about than DI style. – Ryan Stewart Oct 16 '11 at 21:54
25

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.

Ryan Stewart
  • 126,015
  • 21
  • 180
  • 199
  • 1
    Thanks Ryan.As you told "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".Thats what iam trying to understand here in terms of spring, even when dependency is optional ,framework will still inject it in the beginning itself.So what difference it makes in developer life? – M Sach Oct 16 '11 at 06:00
  • *When* something's injected and *if* something's injected are two distinct questions. Optional dependencies fall on the "if" side. – Ryan Stewart Oct 16 '11 at 21:50
17

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.

Ranga Reddy
  • 2,936
  • 4
  • 29
  • 41
  • 3
    Why do you call preventing a circual dependency a disadvantage? I see it as advantage as it prevents the programmer from tight coupling. – the hand of NOD Oct 25 '18 at 08:44
8

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.

Community
  • 1
  • 1
damndemon
  • 331
  • 3
  • 11
1

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,

  1. You will not create new object each time.
  2. You do not need to worry about circular dependency issue(BeanCurrentlyInCreationException).
  3. You will not have to create other fields for class A so you have much more flexible code
Vishnu Dahatonde
  • 179
  • 2
  • 13
0

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.

VedantK
  • 9,728
  • 7
  • 66
  • 71
0

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.
alexis_dia
  • 156
  • 3
  • 13
0

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.

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • 1
    In fact, using constructor injection has the side benefit of making your poorly-designed beans painfully obvious because of the huge constructors. JDK dynamic proxies don't need default constructors. Other frameworks are heading away from default constructors or requiring only a private one. Field injection is my second choice, but then there's the tests... – Ryan Stewart Oct 16 '11 at 21:53
  • yup, for tests there's ReflectionTestUtils. Which is a bit ugly though – Bozho Oct 16 '11 at 21:59
-2

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

user3016087
  • 69
  • 1
  • 2