Spring @Qualifier Annotation with Example
Last Updated :
06 Aug, 2024
Spring is one of the most popular Java EE frameworks. It is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. It made the development of Web applications much easier than compared to classic Java frameworks and application programming interfaces (APIs), such as Java database connectivity (JDBC), JavaServer Pages(JSP), and Java Servlet. This framework uses various new techniques such as Aspect-Oriented Programming (AOP), Plain Old Java Object (POJO), and dependency injection (DI), to develop enterprise applications. Now talking about Spring Annotation
Spring annotations are a form of metadata that provides data about a program. Annotations are used to provide supplemental information about a program. They do not have a direct effect on the operation of the code they annotate and do not change the action of the compiled program.
One of the most important annotations in Spring is the @Qualifier annotation, which is used to resolve ambiguity in bean injection. Let’s understand this with an example.
Note: It is highly recommended that you need first understand the Spring @Autowired Annotation before jumping into @Qualifier Annotation.
Implementation:
Let’s first understand the problem with the @Autowired Annotation then we will understand why @Qualifier Annotation has been introduced. So first let’s create a class named Human and Human class does has a dependency on another class named Heart.
Human.java:
public class Human {
private Heart heart;
}Heart.java:
This class has only one simple method named pump().
public class Heart {
public void pump() {
System.out.println("Heart is Pumping");
}
}Now we want to inject the object of the Heart class inside the Human class by using the @Autowired annotation. So for this thing, we can write the code something like this
Example:
Java
// Java Program to Illustrate Injection of object of the
// Heart class inside the Human class using the @Autowired
// annotation
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
// Class
public class Human {
private Heart heart;
// Annotation
@Autowired public void setHeart(Heart heart)
{
this.heart = heart;
}
// Method
// Calling method of Heart class
public void startPumping() { heart.pump(); }
}
beans.xml:
So in the beans.xml file, we can write the code something like this
XML
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
<bean id="heartObjValue" class="Heart"></bean>
<bean id="humanObject" class="Human"></bean>
</beans>
Main.java:
And in the main class, we can write the code something like this:
Java
// Java Program to Illustrate Application Class
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
// Application class
// Main class
public class Main {
// Main driver method
public static void main(String[] args)
{
// Creating an new class path
ApplicationContext context
= new ClassPathXmlApplicationContext(
"beans.xml");
Human human
= context.getBean("humanObject", Human.class);
human.startPumping();
}
}
Output:
Heart is Pumping
Output Explanation:
In the above code, the @Autowired annotation is used to autowire the Heart object into the Human class by using the Spring Autowiring ‘byType’. When the byType mechanism finds a suitable match, it injects the Heart object without issues.
Note: How @Autowired Work?
- It first tries to resolve dependencies by type.
- If multiple beans of the same type are found, it tries to resolve by name (matching the bean name to the property name).
So in our above example, the “byType” Spring Autowiring mechanism happens and the heart object is injected into the Human class. But where does the problem lie? Now inside the beans.xml file let’s create another bean of the Heart class. We can write the code something like this. Now our modified beans.xml file is:
XML
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
<bean id="humanHeart" class="Heart"></bean>
<bean id="octpusHeart" class="Heart"></bean>
<bean id="humanObject" class="Human"></bean>
</beans>
Here we have two beans of the same class: one is “humanHeart” and another one is “octpusHeart”. In this scenario, the “byType” autowiring will fail because there are two beans of the same type (Heart). Spring will then attempt to resolve by name, but since the property name “heart” doesn’t match either bean id, this also fails.
When you run your application, you’ll get the following exception:
Exception in thread "main" org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'humanObject': Unsatisfied dependency expressed through method 'setHeart' parameter 0; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'Heart' available: expected single matching bean but found 2: humanHeart,octpusHeart
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.resolveMethodArguments(AutowiredAnnotationBeanPostProcessor.java:768)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:720)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:119)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1413)
Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'Heart' available: expected single matching bean but found 2: humanHeart,octpusHeart
at org.springframework.beans.factory.config.DependencyDescriptor.resolveNotUnique(DependencyDescriptor.java:220)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1358)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1300)This is where the @Qualifier Annotation comes into the picture. When “byType” autowiring fails due to multiple candidates, we can use the @Qualifier Annotation to specify exactly which bean should be wired. For example, in the case of the Human class, we need the “humanHeart” bean, so we can specify that bean using the @Qualifier Annotation. Here’s how we can resolve this error:
Example: Modified Human.class File
Java
// Java Program to Illustrate Modified Human Class
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
// Class
public class Human {
private Heart heart;
// Annotation
@Autowired
@Qualifier("humanHeart")
// Setter
public void setHeart(Heart heart)
{
this.heart = heart;
}
// Method
public void startPumping() { heart.pump(); }
}
Output:
Heart is Pumping
One more interesting thing is we can also use these annotations before the dependency. There is no need for any setter method. So we can write something like this also.
Java
// Java Program to Illustrate Modified Human Class
// Where we used these annotations before the dependency
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
// Class
public class Human {
@Autowired @Qualifier("humanHeart") private Heart heart;
// Method
public void startPumping() { heart.pump(); }
}
Conclusion
Spring @Autowired Annotation first looks for matching beans by type (“byType”). If multiple beans of the same type are found, it tries to resolve by name (“byName”). When this automatic resolution fails due to ambiguity, @Qualifier can be used to explicitly specify which bean should be injected.
Please Login to comment...