liveBook · Manning

Field injection

As explained in Spring Start Here, Second Edition

Field injection is a dependency-injection technique that assigns a dependency directly to an object's field.

Field injection places a dependency directly in an object's field. In Spring, annotate the field with @Autowired; Spring supplies a matching bean from its context. section 3.2.1

Figure 3.9 Using the @Autowired annotation over the field, we instruct Spring to provide a value for that field from its context. Spring creates the two beans, person and parrot, and injects the parrot object to the field of the bean of type Person.

Spring creates the Person and Parrot beans, then injects the Parrot into Person's annotated field. section 3.2.1

A person and a parrot

Mark Person and Parrot with @Component, annotate Person's Parrot field with @Autowired, and use @ComponentScan to find them. Retrieving Person from the context shows its injected parrot. A CommentService can likewise receive a repository and notification proxy through annotated fields. section 3.2.1 section 4.2.1

Keep the practical trade-off in mind:

  • Field injection is straightforward and common in examples, proofs of concept, and tests, but is generally avoided in production; constructor injection is preferred for immutability, readability, and testability. section 3.2.1 section 3.6
  • A field injected this way cannot be final. section 3.2.1

How Spring Start Here, Second Edition covers it

How deep it goes
Works through annotated Java examples and bean creation, without detailing Spring's injection internals.
Examples
Demonstrates Person receiving a Parrot and CommentService receiving a repository and notification proxy.
What you can do after
Apply field injection by annotating Spring-managed Java fields with @Autowired.
How it connects
Links field injection to dependency injection, Spring beans, @Autowired, component scanning, and 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.