Senior
Annotation @Primary — in which cases is it needed?
sobes.tech AI
Answer from AI
The @Primary annotation in Spring is used to designate one of several beans of the same type as the preferred one during autowiring.
When there are multiple implementations of an interface or class in the context, and Spring cannot unambiguously choose which bean to inject, @Primary indicates that this bean should be used by default.
Example:
@Component
@Primary
public class MainPaymentService implements PaymentService {
// implementation
}
@Component
public class BackupPaymentService implements PaymentService {
// other implementation
}
// When autowiring PaymentService, MainPaymentService will be selected
@Autowired
private PaymentService paymentService;
Thus, @Primary is needed to avoid conflicts when multiple candidates are available for injection and to explicitly specify the preferred bean.