This repository demonstrates how to handle multiple bean definitions of the same type in a Spring IoC container using the @Qualifier annotation.
When a class (like Human) requires a dependency (like Heart), and the Spring XML configuration defines two different Heart beans, Spring's @Autowired (which performs injection byType) will throw a NoUniqueBeanDefinitionException.
- Enable Annotations: Added
<context:annotation-config/>inbeans.xmlso Spring recognizes annotations inside a pure XML configuration. - Specific Selection: Used
@Qualifier("humanHeart")alongside@Autowiredto tell Spring exactly which bean ID to inject.
dependentBean: Contains theHeartclass.targetBean: Contains theHumanclass (The Target for Injection).qualifier: Contains theMainclass to load the context.beans.xml: Configures twoHeartbeans:humanHeartandoctopusHeartHeart.
<context:annotation-config/>
<bean id="humanHeart" class="org.spring.dependencyinjection.qualifier.dependentBean.Heart" />
<bean id="octopusHeartHeart" class="org.spring.dependencyinjection.qualifier.dependentBean.Heart" />