liveBook · Manning

Constructor injection

As explained in Test Driven: Practical TDD and Acceptance TDD for Java Developers

A form of dependency injection in which dependencies are supplied through an object's constructor.

Constructor injection supplies an object’s dependencies as constructor arguments. Unlike setter injection, it makes the dependencies available when the object is created, avoiding objects that have only some dependencies configured. section 4.4.4

The approach has practical tradeoffs:

  • Long lists of dependencies can clutter a constructor, though they may signal a design flaw. section 4.4.4
  • Framework code cannot use constructor injection to supply dependencies to an existing object, and production code still needs some mechanism to wire dependencies. section 4.4.4

A servlet constraint

A servlet container instantiates LoginServlet, so its AuthenticationService cannot be supplied through constructor injection without overloading the constructor for testing. The example instead postpones the wiring decision and uses an overridable getter to provide a fake service in tests. section 5.2.1

How Test Driven: Practical TDD and Acceptance TDD for Java Developers covers it

How deep it goes
Defines constructor injection and compares its tradeoffs with setter and field injection, without detailing a wiring implementation.
Examples
Uses a LoginServlet and AuthenticationService to illustrate why a servlet container complicates constructor injection.
What you can do after
Evaluate constructor injection’s configuration benefits and limitations, including constraints imposed by framework-created objects.
How it connects
Compares constructor injection with dependency injection, setter injection, and field injection.

Also explained in

Compare how 2 books explain constructor injection →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Test Driven: Practical TDD and Acceptance TDD for Java Developers. The section links point to the parts of the book it draws on.