The @Autowired annotation in depth

When @Autowired is used on a dependency, the application context searches for a matching dependency. By default, all dependencies that are autowired are required.

Possible results are as follows:

  • One match is found: This is the dependency you are looking for
  • More than one match is found: Autowiring fails
  • No match is found: Autowiring fails

Cases where more than one candidate is found can be resolved in two ways:

  • Use the @Primary annotation to mark one of the candidates as the one to be used
  • Use @Qualifier to further qualify autowiring

Get Mastering Spring 5.0 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.