Best practices of dependency injection

For those mandatory dependencies, we should always inject them through constructors. In this way, after creation, the instance will be fully initialized and the dependencies will be read-only. No one can tempt you with dependencies anymore.

For those optional dependencies, we can inject them through setters/methods. 

As for field-based injection, we should avoid using it. Spring makes the field injection by using Java Reflection, and it is considered to be harmful to use field injection. As a matter of fact, it should be avoided for the following reasons:

  • It hides the information of the dependencies, such as how they are initialized and managed, and what these dependencies depend on.
  • Field injection is very easy, as you only need to define a field and apply the @Autowired or @Resource annotation to it. Developers can get addicted to this and add too many dependencies and violate the Single Responsibility Principle (SRP), which we will talk about in Chapter 6, Code Design - Designing for Stability and Extensibility.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.39.60