I am learning autowiring in Spring Boot using @Primary and @Qualifier annotations. I am able to understand that @Primary wires the annotated class as a dependency and in case more than one satisfying classes are found @Qualifier can come to help.
@Component
public class VehicleBean {
@Autowired
@Qualifier("car")
Vehicle car;
public void check() {
car.details();
}
public Vehicle getCar() {
return car;
}
public void setCar(Vehicle car) {
this.car = car;
}
}
Bike
@Component
//@Primary
@Qualifier("car")
public class Bike implements Vehicle {
@Override
public void details() {
System.out.println("Bike is driving");
}
}
Car
@Component
//@Primary
@Qualifier("bike")
public class Car implements Vehicle {
@Override
public void details() {
System.out.println("Car is driving");
}
}
When I add @Qualifier("car")
on my autowired dependency named as "bike" and have @Qualifier("car")
on Car and @Qualifier("bike")
on Bike, it picks up Car. However, when I interchange the @Qualifier
on Bike and Car(e.g - @Qualifier("bike")
on Car and vice versa) it picks up the bike. Also when I change the @Qualifier to "bike on my autowired dependency named as "car" and have @Qualifier("car") on Bike and vice verse, it is picking Car. I was expecting Bike to be picked. What am I missing?