Junior — Middle
Explain the purpose and usage of the @Qualifier annotation in the context of the Spring Framework.
sobes.tech AI
Answer from AI
The @Qualifier annotation in the Spring Framework is used to specify which exact bean should be injected when there are multiple candidates of the same type in the context.
By default, Spring injects beans by type. If there are multiple beans of the same type, ambiguity arises, and Spring throws an exception. To resolve this, @Qualifier is used.
Example of usage:
@Component
@Qualifier("fastService")
public class FastPaymentService implements PaymentService {
// implementation
}
@Component
@Qualifier("secureService")
public class SecurePaymentService implements PaymentService {
// implementation
}
@Service
public class OrderService {
private final PaymentService paymentService;
public OrderService(@Qualifier("fastService") PaymentService paymentService) {
this.paymentService = paymentService;
}
}
In this example, the bean with the qualifier "fastService" will be used when injecting into OrderService.
Thus, @Qualifier helps manage the selection of a specific implementation among multiple candidates of the same type.