In Spring, when you have multiple beans of the same type, Spring gets confused about which one to inject. This is where @Qualifier comes in — it helps Spring choose the exact bean you want.
💬 Why is @Qualifier Needed?
Imagine this scenario:
public interface Vehicle {
void start();
}
Now you create two beans:
@Component
public class Car implements Vehicle {
public void start() {
System.out.println("Car starting...");
}
}
@Component
public class Bike implements Vehicle {
public void start() {
System.out.println("Bike starting...");
}
}
Now if you try this:
@Autowired
private Vehicle vehicle;
Spring throws an error: “No unique bean of type Vehicle” because it found 2 beans (Car and Bike). It doesn’t know which one to inject.
✅ Solution: Use @Qualifier
@Autowired
@Qualifier("bike")
private Vehicle vehicle;
Spring will now inject the Bike bean.
.
🛠 How It Works
@Qualifier matches the bean name.
The name can be:
Method name in @bean factory method
Class name (by default)
Name provided explicitly in @Component("customName")
💡 You Can Also Use It in Constructor
public MyService(@Qualifier("car") Vehicle vehicle) {
this.vehicle = vehicle;
}
Example
VechicleController
package com.example.demo.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.servic.VehicleService;
@RestController
public class VehicleController {
private final VehicleService vehicleService;
public VehicleController(VehicleService vehicleService) {
this.vehicleService = vehicleService;
}
@GetMapping("/start")
public String start() {
vehicleService.startVehicle();
return "Vehicle started successfully!";
}
}
VehicleService
package com.example.demo.servic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import com.example.demo.model.Vehicle;
@Service
public class VehicleService {
Vehicle vehicel;
@Autowired
public VehicleService(@Qualifier("car") Vehicle vehicel) {
this.vehicel = vehicel;
}
public void startVehicle() {
vehicel.start();
}
}
Vehicle interface
package com.example.demo.model;
public interface Vehicle {
void start();
}
Car class
package com.example.demo.model;
import org.springframework.stereotype.Component;
@Component
public class Car implements Vehicle{
@Override
public void start() {
System.out.println("Car is starting ");
}
}
Bike Class
package com.example.demo.model;
import org.springframework.stereotype.Component;
@Component
public class Bike implements Vehicle{
@Override
public void start() {
System.out.println("Bike is starting ");
}
}