Spring Framework FAQ: Top Questions
11. What is the purpose of the @Qualifier annotation in Spring?
@Qualifier
is used to resolve the conflict when multiple beans of the same type are present in the Spring context and one needs to be injected.
πΊοΈ Step-by-Step:
- Declare multiple beans of the same type with different names.
- Use
@Qualifier("beanName")
to specify which one to inject.
π₯ Example Input:
@Component("engineV6")
public class V6Engine implements Engine {}
@Component("engineV8")
public class V8Engine implements Engine {}
@Autowired
@Qualifier("engineV8")
private Engine engine;
π Expected Output:
V8Engine instance is injected into the 'engine' field.
π Detailed Explanation:
- Avoids ambiguity: Prevents
NoUniqueBeanDefinitionException
. - Fine-grained control: Explicitly defines which bean to use.
π οΈ Use Cases:
- Multiple data sources or strategy implementations.
- Injecting test/mock beans selectively in unit tests.