Skip to main content
7 of 7
replaced http://stackoverflow.com/ with https://stackoverflow.com/

Dependency Injection: Field Injection vs Constructor Injection?

I know this is a hot debate and the opinions tend to change over time as to the best approach practice.

I used to use exclusively field injection for my classes, until I started reading up on different blogs (exs: petrikainulainen and schauderhaft and fowler) about the benefits of constructor injection. I have since switched my methodologies to use constructor injection for required dependencies and setter injection for optional dependencies.

However, I have recently gotten into a debate with the author of JMockit - a mocking framework - in which he sees constructor & setter injection as bad practice and indicates that the JEE community agrees with him.

In today's world, is there a preferred way of doing injection? Is Field injection preferred?

Having switched to constructor inject from field injection in the last couple of years, I find it a lot clearer to use, but I am wondering if I should re-examine my viewpoint. The author of JMockit (Rogério Liesenfeld), is clearly well versed in DI, so I feel obligated to review my approach given that he feels so strongly against constructor/setter injection.

Eric B.
  • 1.2k
  • 1
  • 9
  • 14