When to use constructor injection in Spring?
I heard that constructor injection is particularly useful when you absolutely must have an instance of the dependency class before your component is used. But what does it mean?
Can anybody explain me with some simple examples the following moments:
- What are the benefits that I will get using constructor injection?
- What is dynamic constructor injection?
The correct approach is to use constructor injection whenever it's possible. Thanks to that it's clear what are the object dependencies and you are not able to create one if you do not provide all that are required.
Use constructor injection as below.
final
fields make sure that dependencies are not changed after object is initializedAssert.notNull
makes sure that you don't put null values instead of real objects.When you use setter injection or field injection your API lets you create object in incorrect state. Consider an example:
For all not optional dependencies you can use setter injection. Read more on Oliver Gierke (Spring Data lead) blog: http://olivergierke.de/2013/11/why-field-injection-is-evil/
Update 15.01.2019
Starting from Spring 4.3 there is no need to put
@Autowired
annotation on the constructor if only single constructor is present.