Junior — Middle
What is the purpose of the Qualifier annotation in the Spring framework for dependency injection?
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.
For example, if there are two beans of the same interface, Spring cannot choose which one to inject without @Qualifier, and it will throw an error. Using @Qualifier, you can explicitly specify the name of the desired bean.
Example:
@Component("beanA")
public class BeanA implements MyService {}
@Component("beanB")
public class BeanB implements MyService {}
@Service
public class MyConsumer {
private final MyService myService;
public MyConsumer(@Qualifier("beanA") MyService myService) {
this.myService = myService;
}
}
Here, @Qualifier("beanA") tells Spring to inject the bean named "beanA".