liveBook · Manning

Constructor injection

As explained in Spring Start Here, Second Edition

Constructor injection is a dependency-injection technique that supplies an object's dependencies through its constructor parameters.

Constructor injection supplies an object’s dependencies through its constructor parameters. In Spring, the framework passes matching beans from its context when it creates the object. section 3.2.2

Declare a constructor parameter for each dependency, assign it to a field, and make the field final when it should not change after initialization. Spring can wire the dependency without changes to the configuration class. A single-constructor class does not need @Autowired starting with Spring 4.3. section 3.2.2

A person with a parrot

A Person constructor accepts a Parrot and assigns it to a final field. Spring supplies the Parrot bean, linking the two instances; the same constructor can also receive a Parrot directly in a unit test without Spring. section 3.2.2

Figure 3.10 When you define a parameter of the constructor, Spring provides a bean from its context as a value to that parameter when calling the constructor.

Shows Spring providing a context bean as a constructor argument. section 3.2.2

Constructor injection is generally preferred over field and setter injection because it supports immutability, readability, and testability. If several beans match a parameter’s type, Spring may need additional guidance, such as @Primary or @Qualifier. section 3.6 section 3.4

How Spring Start Here, Second Edition covers it

How deep it goes
Explains constructor syntax, final fields, testing benefits, and annotation omission, but does not detail injection internals.
Examples
Demonstrates a Person receiving a Parrot and a CommentService receiving repository and notification dependencies.
What you can do after
Build it from scratch by defining a constructor that accepts and assigns the required dependencies.
How it connects
Connects dependency injection with inversion of control, Spring beans, and field and setter injection.

Also explained in

Compare how 3 books explain constructor injection →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Spring Start Here, Second Edition. The section links point to the parts of the book it draws on.