Lets say we have a Coach interface:
public interface Coach {
public String getDailyWorkout();
}
And 2 different implementations for the Coach interface:
@Component
public class CricketCoach implements Coach{
@Override
public String getDailyWorkout() {
return "Practice fast bowling for 15 minutes!!";
}
}
@Component
public class BaseballCoach implements Coach{
@Override
public String getDailyWorkout() {
return "Spend 30 minutes in batting practice";
}
}
And my controller where use constructor injection in order to get the implementation from above. Let's say I want a BaseballCoach injected. In order to do so we can use the annotation @Qualifier like so:
@RestController
public class DemoController {
private Coach myCoach;
@Autowired
public void DemoController(@Qualifier("baseballCoach")Coach myCoach) {
this.myCoach = myCoach;
}
@GetMapping("/dailyworkout")
public String getDailyWorkout() {
return myCoach.getDailyWorkout();
}
}
Why would we even use the qualifier if I could just use the "correct" class like so:
@RestController
public class DemoController {
private Coach myCoach;
@Autowired
public void DemoController(BaseballCoach myCoach) {
this.myCoach = myCoach;
}
@GetMapping("/dailyworkout")
public String getDailyWorkout() {
return myCoach.getDailyWorkout();
}
}
Or even so the correct class in the variable "type"
@RestController
public class DemoController {
private BaseballCoach myCoach;
@Autowired
public void DemoController(BaseballCoach myCoach) {
this.myCoach = myCoach;
}
@GetMapping("/dailyworkout")
public String getDailyWorkout() {
return myCoach.getDailyWorkout();
}
}
Are there any benefits to using the qualifier? Or is it just the recommended method to do so?