liveBook · Manning

Qualifier annotation

As explained in Spring Start Here, Second Edition

The @Qualifier annotation identifies which bean should be selected when multiple beans match an injection point.

When several Spring beans match an injection point, Spring needs a way to choose. @Qualifier names the specific bean to inject, instead of leaving the choice ambiguous. For example, @Qualifier("parrot2") Parrot parrot2 selects the bean named parrot2; without guidance or a primary bean, Spring can fail because it found multiple matches. section 3.4 section 4.2.2

Use @Qualifier at the injection point to choose explicitly. Unlike @Primary, which marks a default bean, a qualifier lets different consumers select different implementations of the same interface. section 4.2.2 section 4.5

Listing 4.15 Specifying the implementation Spring needs to inject with @Qualifier
@Component
public class CommentService {
 
  private final CommentRepository commentRepository;
 
  private final CommentNotificationProxy commentNotificationProxy;
 
  public CommentService(   #A
    CommentRepository commentRepository,
    @Qualifier("PUSH") CommentNotificationProxy commentNotificationProxy) {
 
    this.commentRepository = commentRepository;
    this.commentNotificationProxy = commentNotificationProxy;
  }
 
  // Omitted code
}

The constructor parameter’s @Qualifier("PUSH") directs Spring to inject the push-notification implementation. section 4.2.2

How Spring Start Here, Second Edition covers it

How deep it goes
Explains bean-name selection at method and constructor injection points, and contrasts explicit choice with a default bean.
Examples
Uses two Parrot beans and push-versus-email notification implementations to demonstrate explicit selection.
What it assumes
Assumes an injection point with multiple matching beans and explains that Spring needs guidance to choose.
What you can do after
Apply it by naming the desired bean at an injection point, including a constructor parameter.
How it connects
Connects dependency injection with beans, interfaces, and @Primary.

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.