Bean conflicts occur when Spring finds multiple beans of the same type and cannot determine which one should be injected. Spring Boot provides several mechanisms to resolve such conflicts, allowing developers to explicitly control bean selection and dependency injection behavior.
Key Points: • @Qualifier is used to specify exactly which bean should be injected. • @Primary marks a bean as the default choice when multiple candidates exist. • Proper bean naming and profile-based configurations help avoid conflicts in large applications.
Example: Suppose an application has two payment implementations:
• CreditCardPaymentService • PayPalPaymentService
When Spring tries to inject PaymentService, it finds multiple implementations and throws a NoUniqueBeanDefinitionException unless the conflict is resolved.
Code Example:
@Service
public class CreditCardPaymentService
implements PaymentService {
}
@Service
public class PayPalPaymentService
implements PaymentService {
}Using @Qualifier:
@Service
public class OrderService {
private final PaymentService paymentService;
@Autowired
public OrderService(
@Qualifier("payPalPaymentService")
PaymentService paymentService) {
this.paymentService = paymentService;
}
}Other Ways to Resolve Bean Conflicts:
1. Using @Primary
@Primary
@Service
public class CreditCardPaymentService
implements PaymentService {
}• Spring automatically selects this bean by default.
2. Using Bean Names
@Bean("paypalService")
public PaymentService paymentService() {
return new PayPalPaymentService();
}• Inject using the bean name with @Qualifier.
3. Using Profiles
@Profile("dev")
@Service
public class MockPaymentService
implements PaymentService {
}
@Profile("prod")
@Service
public class RealPaymentService
implements PaymentService {
}• Only one bean is loaded based on the active profile.
4. Using @Conditional Annotations
• Create beans conditionally based on properties, classes, or custom conditions.
Common Exceptions:
NoUniqueBeanDefinitionException
Occurs when: • Multiple beans of the same type exist. • Spring cannot determine which bean to inject.
Best Practices: • Use @Qualifier when a specific implementation is required. • Use @Primary for the most commonly used implementation. • Use Profiles for environment-specific beans. • Keep bean names meaningful and unique.
Interview Tip: A concise interview answer is: Bean conflicts occur when multiple beans of the same type are available for injection. The most common solution is using @Qualifier to explicitly specify the required bean. Spring Boot also provides @Primary, Profiles, bean naming, and conditional bean creation mechanisms to resolve such conflicts effectively.