Spring Boot: @Primary vs @Qualifier Annotation

🌱 Spring Boot tip @Primary vs @Qualifier When you have multiple implementations of the same interface, Spring doesn't know which bean to inject. That's where these two annotations come in. @Primary → marks the default implementation. Spring picks it automatically when no specific choice is made. @Qualifier → overrides @Primary. You point Spring to exactly the bean you want by name. ------------------- Example: ------------------- @Service @Primary // default choice public class CreditCardService implements PaymentService { } @Service public class PayPalService implements PaymentService { } // Gets CreditCardService (Primary) @Autowired private PaymentService paymentService; // Gets PayPalService (Qualifier wins) @Autowired @Qualifier("payPalService") private PaymentService paymentService; Skip both and have two beans of the same type → Spring throws NoUniqueBeanDefinitionException. Simple rule: → @Primary = "use me by default" → @Qualifier = "no, use this specific one" #Java #SpringBoot #BackendDevelopment #SoftwareEngineering #ContinousLearning

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories