Skip to content

harman-04/spring-dependency-injection-autowired-qualifier

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Spring @Autowired & @Qualifier Resolution

This repository demonstrates how to handle multiple bean definitions of the same type in a Spring IoC container using the @Qualifier annotation.

The Challenge: Bean Ambiguity

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.

The Solution

  1. Enable Annotations: Added <context:annotation-config/> in beans.xml so Spring recognizes annotations inside a pure XML configuration.
  2. Specific Selection: Used @Qualifier("humanHeart") alongside @Autowired to tell Spring exactly which bean ID to inject.

Project Structure

  • dependentBean: Contains the Heart class.
  • targetBean: Contains the Human class (The Target for Injection).
  • qualifier: Contains the Main class to load the context.
  • beans.xml: Configures two Heart beans: humanHeart and octopusHeartHeart.

Configuration Snippet

<context:annotation-config/>

<bean id="humanHeart" class="org.spring.dependencyinjection.qualifier.dependentBean.Heart" />
<bean id="octopusHeartHeart" class="org.spring.dependencyinjection.qualifier.dependentBean.Heart" />

About

Demonstrating Spring @Autowired and @qualifier annotations within an XML-configured project to resolve bean ambiguity (Human/Heart scenario).

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages