The Wayback Machine - https://web.archive.org/web/20240915143227/https://www.geeksforgeeks.org/spring-qualifier-annotation-with-example/
Open In App

Spring @Qualifier Annotation with Example

Last Updated : 06 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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?

  1. It first tries to resolve dependencies by type.
  2. 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.



Previous Article
Next Article

Similar Reads

Spring @Controller Annotation with Example
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 t
4 min read
Spring - @PostConstruct and @PreDestroy Annotation with Example
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 t
13 min read
Spring @Repository Annotation with Example
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 t
5 min read
Spring @Service Annotation with Example
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 t
4 min read
Spring @ResponseBody Annotation with Example
Spring Annotations allow us to configure dependencies and implement dependency injection through java programs. Those are used to provide supplemental information about a program. It does not have a direct effect on the operation of the code they annotate. It does not change the action of the compiled program. The @ResponseBody annotation tells a c
5 min read
Spring @ComponentScan Annotation with Example
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 t
4 min read
Spring @Bean Annotation with Example
One of the most important annotations in spring is the @Bean annotation which is applied on a method to specify that it returns a bean to be managed by Spring context. Spring Bean annotation is usually declared in Configuration classes methods. This annotation is also a part of the spring core framework. So let's understand @Bean Annotation with an
8 min read
Spring @Configuration Annotation with Example
One of the most important annotations in spring is @Configuration annotation which indicates that the class has @Bean definition methods. So Spring container can process the class and generate Spring Beans to be used in the application. This annotation is part of the spring core framework. So let's understand @Configuration Annotation with an examp
4 min read
Spring @RequestMapping Annotation with Example
One of the most important annotations in spring is the @RequestMapping Annotation which is used to map HTTP requests to handler methods of MVC and REST controllers. In Spring MVC applications, the DispatcherServlet (Front Controller) is responsible for routing incoming HTTP requests to handler methods of controllers. When configuring Spring MVC, yo
6 min read
Spring @Value Annotation with Example
One of the most important annotations in spring is @Value annotation which is used to assign default values to variables and method arguments. We can read spring environment variables as well as system variables using @Value annotation. It also supports Spring Expression Language (SpEL). It is generally used for injecting values into configuration
6 min read
Spring @Component Annotation with Example
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 c
4 min read
Spring Boot - @LoadBalanced Annotation with Example
The @LoadBalanced annotation creates an instance of created RestTemplate load-balanced. There is no code you need to write to make the RestTemplate load-balance HTTP request it sends to an internal microservice. The RestTemplate bean will be intercepted and auto-configured by Spring Cloud. In brief, we need to use the @LoadBalanced Annotation in ou
11 min read
Spring MVC @SessionAttributes Annotation with Example
In the ever-evolving world of web development, a constant challenge is to seamlessly manage data between requests. Enter Spring MVC's @SessionAttributes annotation, a powerful solution that elegantly manages the session attributes of a Spring application. This markup becomes a lifesaver when certain information must persist throughout the interacti
3 min read
Spring MVC @ModelAttribute Annotation with Example
In Spring MVC, the @ModelAttribute annotation binds a method parameter or method return value to a named model attribute and then exposes it to a web view. It refers to the property of the Model object. For example, if we have a form with a form backing object that is called "Student" then we can have Spring MVC supply this object to a Controller m
8 min read
Spring @Required Annotation with Example
Spring Annotations allow us to configure dependencies and implement dependency injection through java programs. Those are a form of metadata that provides data about a program. The @Required annotation in spring is a method-level annotation used in the setter method of a bean property and therefore making the setter-injection compulsory. This annot
6 min read
Spring - When to Use @Qualifier and @Autowired For Dependency Injection
In the world of Spring Framework, managing dependencies is a fundamental aspect of building robust and maintainable applications. Spring offers two primary annotations to facilitate dependency injection: @Autowired and @Qualifier. Understanding when and how to use these annotations is crucial for effective bean wiring .@Autowired and @Qualifier are
6 min read
Spring @Autowired Annotation
The @Autowired annotation marks a Constructor, Setter method, Properties and Config() method as to be autowired that is 'injecting beans'(Objects) at runtime by Spring Dependency Injection mechanism which is clearly depicted from the image below as shown: Enabling @Autowired annotation Spring beans can be declared either by Java configuration or XM
3 min read
Spring - Required Annotation
Consider a scenario where a developer wants to make some of the fields as mandatory fields. using the Spring framework, a developer can use the @Required annotation to those fields by pushing the responsibility for such checking onto the container. So container must check whether those fields are being set or not. The Spring Framework supports a nu
7 min read
Spring - MVC RequestParam Annotation
@RequestParam annotation enables spring to extract input data that may be passed as a query, form data, or any arbitrary custom data. Here, we will see how we can use @RequestParam when building RESTful APIs for a web-based application. Context of the Application: Let us suppose we are implementing a sample feature for the 'Geeksforgeeks' web appli
5 min read
Spring AOP - AspectJ Annotation
AOP i.e Aspect-Oriented Programming complements OOP by enabling modularity of cross-cutting concerns. @AspectJ is mainly used for declaring aspects as regular Java classes annotated with annotations. Spring AspectJ AOP implementation has many annotations. They are explained below: @Aspect: It declares the class as an aspect.@Pointcut: It declares t
4 min read
Difference Between @Controller and @RestController Annotation in Spring
Spring Annotations are a form of metadata that provides data about a program. Annotations are used to provide supplemental information about a program. It does not have a direct effect on the operation of the code they annotate. It does not change the action of the compiled program. @Controller Annotation: Spring @Controller annotation is also a sp
3 min read
Difference Between @Controller and @Service Annotation in Spring
Spring Annotations are a form of metadata that provides data about a program. Annotations are used to provide supplemental information about a program. It does not have a direct effect on the operation of the code they annotate. It does not change the action of the compiled program. Spring @Controller AnnotationSpring @Controller annotation is a sp
5 min read
How to Capture Data using @RequestParam Annotation in Spring?
@RequestParam annotation enables spring to capture input data that may be passed as a query, form data, or any arbitrary custom data. It is used to bind a web request parameter to a method parameter. Here we are going to understand these two above lines and we will see how can we capture data using this annotation. Let's create a simple MVC applica
7 min read
Spring @Primary Annotation
@Primary annotation in Spring is used to indicate the primary bean when multiple beans of the same type are present for auto wiring. When multiple beans are eligible for auto wiring the @Primary annotation will help to determine which bean should be given preference. By applying @Primary annotation to a specific bean we are specifying that it is a
4 min read
Spring - @PostMapping and @GetMapping Annotation
Spring Annotations are a form of metadata that provides data about a program. Annotations are used to provide supplemental information about a program. It does not have a direct effect on the operation of the code they annotate. It does not change the action of the compiled program. What is meant by @PostMapping annotation?@PostMapping annotation i
3 min read
Spring - @DeleteMapping and @PutMapping Annotation
Spring Annotations are a form of metadata that provides data about a program. Annotations are used to provide supplemental information about a program. It does not have a direct effect on the operation of the code they annotate. It does not change the action of the compiled program. What is meant by @DeleteMapping annotation?@DeleteMapping annotati
4 min read
Difference Between @RequestBody and @ResponseBody Annotation in Spring
To achieve the functionality of handling request data and response data in Spring MVC, @RequestBody and @ResponseBody annotations are used. So, in this article, we will go dive into the difference between @RequestBody and @ResponseBody annotations with an example. @RequestBody@RequestBody is mainly used with CRUD Operations to read the request body
3 min read
Working with Cookies in Spring MVC using @CookieValue Annotation
Cookies are the concept of storing user information on the client side in the form of a text file. In this text file lot of information is available about clients or users. Cookies are small pieces of data that are sent by the web servers to the user's web browsers and those cookies are stored in the client only, the cookies play an important role
8 min read
Spring MVC context:annotation-config VS context:component-scan
In this article, we will learn about Spring MVC &lt;context:annotation-config&gt; vs &lt;context:component-scan&gt;. Activating all annotations existing in Java beans that have already been registered either by definition in an application context file or by component scanning is the primary function of annotation-config. The requirement for regist
3 min read
Spring Boot - @Async Annotation
Synchronization means every process or thread should be Synchronized together. It means executing process by process that's we can say Synchronization. This is used when one task is complete and only then does another task want to come and be executed. so It looks like there are some limitations. That's why asynchronization comes into the picture.
2 min read