liveBook · Manning

@Autowired

As explained in Spring Start Here, Second Edition

The Spring @Autowired annotation marks a constructor, field, or method for automatic dependency injection.

@Autowired marks a place where Spring should supply a dependency from its context. It makes the relationship between collaborating beans visible in the class that needs the dependency. section 3.2

The annotation supports three injection styles:

  • Field injection is quick to write and common in examples and tests, but is generally avoided in production code. section 3.2.1
  • Constructor injection is preferred for real projects; it supports immutability, readability, and testability. section 3.2 section 3.6
  • Setter injection exists but is uncommon; it can be harder to read and does not allow a final dependency field. section 3.2.3

A person and a parrot

With Person and Parrot registered as Spring beans, marking Person’s parrot field with @Autowired lets Spring inject the Parrot instance. When several beans have the same type, use @Qualifier to identify the intended one. section 3.2.1 section 3.4

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.

The diagram shows Spring creating the Person and Parrot beans and injecting the Parrot into the Person field. section 3.2.1

How Spring Start Here, Second Edition covers it

How deep it goes
Compares field, constructor, and setter injection, favoring constructors while noting setter injection is uncommon.
Examples
Demonstrates field injection with Person and Parrot, and uses @Qualifier to select between multiple Parrot beans.
What you can do after
Apply it to let Spring supply a bean through a field, constructor, or setter; prefer constructor injection in real projects.
How it connects
Connects dependency injection with Spring beans, inversion of control, and @Qualifier for choosing among same-type beans.

Also explained in

Compare how 3 books explain @Autowired →

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.