Spring @Qualifier Annotation with Example (original) (raw)

Last Updated : 16 Jan, 2026

The @Qualifier annotation is used to resolve ambiguity when multiple beans of the same type are available for dependency injection. It helps specify which exact bean should be injected into a class when Spring cannot automatically determine the correct one.

Key features of @Qualifier Annotation:

How @Autowired Works Internally

Spring resolves dependencies in the following order:

This is where @Qualifier becomes necessary.

Problem with @Autowired Annotation

To understand the need for the @Qualifier annotation, let’s first look at a scenario where the @Autowired annotation can cause issues. Consider a Human class that depends on a Heart class. The Heart class has a simple method called pump()

Heart.java

Java `

public class Heart { public void pump() { System.out.println("Heart is Pumping"); } }

`

**Explanation:

Human.java

Human class does has a dependency on another class named Heart.

Java `

import org.springframework.beans.factory.annotation.Autowired;

public class Human { private Heart heart;

@Autowired
public void setHeart(Heart heart) {
    this.heart = heart;
}

public void startPumping() {
    heart.pump();
}

}

`

**Explanation:

beans.xml (Single Bean)

XML `

context:annotation-config/

`

**Output

Heart is Pumping

**Explantion:

It Works correctly because only one Heart bean exists.

Multiple Beans of Same Type

This configuration shows the real problem that occurs when Spring finds multiple beans of the same type during autowiring.

beans.xml (Multiple Bean)

XML `

context:annotation-config/

`

**Output

NoUniqueBeanDefinitionException

**Explanation:

Solution: Using @Qualifier Annotation

When multiple beans of the same type exist, @Qualifier helps specify which one to inject. For example, in the Human class, we can use @Qualifier("humanHeart") to avoid confusion and ensure the correct bean is wired.

Human.java (Setter Injection)

Java `

import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier;

public class Human {

private Heart heart;

@Autowired
@Qualifier("humanHeart")
public void setHeart(Heart heart) {
    this.heart = heart;
}

public void startPumping() {
    heart.pump();
}

}

`

**Output:

Heart is Pumping

**Explanation:

Alternative: Using @Qualifier on Field Injection

We can also use the @Qualifier annotation directly on the field, eliminating the need for a setter method.

**Example: This code demonstrates field injection using @Autowired and @Qualifier to inject a specific Heart bean.

Java `

import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier;

public class Human { @Autowired @Qualifier("humanHeart") private Heart heart;

public void startPumping() {
    heart.pump();
}

}

`

**Explanation:

Advantages of @Qualifier