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
