Injection using the setter method versus the constructor

There are two straightforward options of DI – setter- or constructor-based DI. Both of these methods perform the same operation—injecting dependencies—but at different times of the object's lifespan. One happens during object instantiation, while the other happens on calling the setter method explicitly.

A very obvious dilemma comes into the picture when you implement DI with these two options. Understanding the difference is important because it reflects the basic problem of the object-oriented programming context: do we initiate the field variable with the constructor argument or through the setter method?

Get Java 9 Dependency Injection now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.