Logo InterviewVault

Welcome back, Sujit Kumar Mishra

SKM

Revision Mode

Document technical questions and best-practice answers.

Cancel

What is @Qualifier annotation in SpringBoot? 

The @Qualifier annotation in Spring Boot is used to tell Spring exactly which bean to use when there are multiple beans of the same type.


Think of it like this:

If you have two beans of the same type (for example, two different implementations of an interface), Spring needs to know which one you want to use. By adding @Qualifier("beanName") next to your dependency, you are specifying the exact bean you want.


Example:

@Autowired
@Qualifier("myBean")
private MyService myService;

This tells Spring to inject the bean named myBean into myService.


In short:

@Qualifier helps avoid confusion when there are multiple beans of the same type by specifying which one to use.


Here’s a complete and easy-to-understand example of using @Qualifier in Spring Boot

Suppose you have an interface called Animal and two implementations: Dog and Cat. You want to tell Spring which one to inject.


Step 1: Create the interface

public interface Animal {
  void makeSound();
}

Step 2: Create two implementations

import org.springframework.stereotype.Component;

@Component("dog")
public class Dog implements Animal {
  public void makeSound() {
    System.out.println("Woof!");
  }
}

@Component("cat")
public class Cat implements Animal {
  public void makeSound() {
    System.out.println("Meow!");
  }
}

Step 3: Use @Qualifier to specify which bean to inject

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

@Service
public class AnimalService {

  @Autowired
  @Qualifier("dog") // Change to "cat" if you want the Cat bean
  private Animal animal;

  public void play() {
    animal.makeSound();
  }
}

Step 4: Run the service

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.beans.factory.annotation.Autowired;

@SpringBootApplication
public class DemoApplication implements CommandLineRunner {

  @Autowired
  private AnimalService animalService;

  public static void main(String[] args) {
    SpringApplication.run(DemoApplication.class, args);
  }

  @Override
  public void run(String... args) throws Exception {
    animalService.play(); // Output: Woof!
  }
}

Summary:

1: @Qualifier("dog") tells Spring to inject the Dog bean.

2: If you want the Cat bean, just change it to @Qualifier("cat").


This is how you use @Qualifier to choose between multiple beans of the same type!

Ready for commit