Constructor injection Vs Field injection in Java
2 min readAug 19, 2020
In this short article I gonna walk you through constructor injection in spring boot Vs field injection and why we should avoid field in injection in our daily coding life.
First of all, there are three ways on how to handle and write dependency injection in your code in spring boot and in java in general:
- Through a constructor.
- Through setters or other methods.
- Through reflection, directly into fields.
Constructor injection pros:
- Better testability. You do not need any mocking library or a Spring context in unit tests. You can create an object that you want to test with the new keyword. Such tests are always faster because they not rely on the reflection mechanism.
- Immutability. Once the dependencies are set they cannot be changed.
- The dependencies can be final, which helps with robustness and thread-safety.
- Cleaner expression of mandatory dependencies. Field injection is ambiguous in this matter.
Constructor injection cons:
- More code (but modern IDEs like Intellij alleviate the pain).
Field injection drawbacks
- You cannot create immutable objects, as you can with constructor injection
- Your classes have tight coupling with your DI container and cannot be used outside of it
- Your classes cannot be instantiated (for example in unit tests) without reflection. You need the DI container to instantiate them, which makes your tests more like integration tests
- Your real dependencies are hidden from the outside and are not reflected in your interface (either constructors or methods)
- It is really easy to have like ten dependencies. If you were using constructor injection, you would have a constructor with ten arguments, which would signal that something is fishy. But you can add injected fields using field injection indefinitely. Having too many dependencies is a red flag that the class usually does more than one thing, and that it may violate the Single Responsibility Principle.