liveBook · Manning

Primary annotation

As explained in Spring Start Here, Second Edition

The @Primary annotation marks a Spring bean as the preferred candidate when multiple beans match a dependency.

When the Spring context contains several beans that match a requested type, Spring needs help choosing one. The @Primary annotation marks a bean as the default candidate when no specific bean is named. Without a clear choice, Spring can report a NoUniqueBeanDefinitionException. section 4.2.2 section 2.1

Make a bean the default

If several Parrot beans exist, annotate one @Bean method with @Primary: @Bean @Primary Parrot parrot2() { var p = new Parrot(); p.setName("Miki"); return p; } A lookup by Parrot type without a name now selects Miki. A lookup by bean name can still select a different bean. section 2.1

The same idea works with implementations of an interface. If both email and push notification beans implement CommentNotificationProxy, Spring needs to know which one to inject. Place @Primary alongside @Component on the implementation that should be the default. section 4.2.2

Listing 4.14 Using @Primary to mark the implementation as default
@Component
@Primary    #A
public class CommentPushNotificationProxy
  implements CommentNotificationProxy {    
 
  @Override
  public void sendComment(Comment comment) {
    System.out.println(
      "Sending push notification for comment: " 
          + comment.getText());
  }
}

The push notification implementation is registered as a component and marked as the default candidate. section 4.2.2

Use @Primary when one implementation should be the default. Use @Qualifier to choose a specific bean by name when different dependencies need different implementations. A custom implementation can also be marked primary when a dependency already supplies an implementation. section 4.2.2

How Spring Start Here, Second Edition covers it

How deep it goes
Explains default selection through annotated component classes and @Bean methods, including the ambiguity exception and named alternatives.
Examples
Uses multiple Parrot beans and email and push notification implementations to demonstrate default selection.
What you can do after
Apply it via Spring to designate a default bean and distinguish that choice from selecting a named bean.
How it connects
Connects Spring beans and dependency injection with Java interfaces, @Component, @Bean, and @Qualifier.

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.