Eğer ki biz bir öğretmenin ismini @Qualifier ile belirtmek istemiyorsak; @Primary annotationunu kullanabiliriz. Burdaki ana mevzu şudur biz bir tane öğretmenin gelmesini ama hangi öğretmen olmasını istemiyorsak yani specific belirtmiyorsak istediğimiz class'a verebiliriz. Class'a eklememiz gereken tek özellik, "@Primary"'dir.
@Component
@Primary
public class MathTeacher implements Teacher{
@Override
public String getName() {
return "Minter Math";
}
}@RestController
public class PrimaryRestController {
private final Teacher teacher;
@Autowired
public PrimaryRestController(Teacher teacher) {
this.teacher = teacher;
}
@RequestMapping(path="/primary",method=RequestMethod.GET)
public String getTeacherName(){
return this.teacher.getName();
}
}- Eğer ki biz hem @Qualifier hemde @Primary annotationunu birlikte kullanırsak; @Qualifier daha fazla önceliğe sahiptir yani @Qualifier'da hangisi kullanılmışsa o class inject edilir.
Örneğin MathTeacher'da @Primary kalsın. Ayrıca RestController'ımıza da @Qualifier ekleyelim.
@RestController
public class PrimaryRestController {
private final Teacher teacher;
@Autowired
public PrimaryRestController(@Qualifier("englishTeacher") Teacher teacher) {
this.teacher = teacher;
}
@RequestMapping(path="/primary",method=RequestMethod.GET)
public String getTeacherName(){
return this.teacher.getName();
}
}
Qualifier daha fazla önceliğe sahip olduğu için ve daha çok specific olarak belirtim bulunduğundan dolay kullanmak tavsiye edilir çünkü @Primary'i farklı classlarda da kullanırsak eğer hata verir.