Junior — Middle
Can you explain the purpose and use of the @Qualifier annotation in Spring?
sobes.tech AI
Answer from AI
The @Qualifier annotation in Spring is used to specify which exact bean should be injected when there are multiple candidates of the same type in the context.
When multiple beans of the same class or interface are defined in the application, Spring cannot unambiguously decide which one to inject during autowiring (@Autowired). To resolve this ambiguity, @Qualifier is used with the name of the desired bean.
Example:
@Component("beanOne")
public class MyService implements ServiceInterface { }
@Component("beanTwo")
public class AnotherService implements ServiceInterface { }
@Component
public class Client {
private final ServiceInterface service;
@Autowired
public Client(@Qualifier("beanTwo") ServiceInterface service) {
this.service = service;
}
}
In this example, @Qualifier("beanTwo") indicates that the bean named "beanTwo" should be injected.
Thus, @Qualifier helps manage the selection of a specific bean when multiple candidates of the same type are present.