Thursday, February 17, 2022

Spring @Qualifier Annotation

 There is a possibility to have more than one bean with same type, in this case your IDE will show the error like 'Could not autowire. There is more than one bean of '' Type'.  This says we need to explicitly specify the name for the Object. This can done by using @Qualifier annotation. Spring provide this annotation to specify the name. 

Here I have Chef Interface, VegChef, NonVegChef component implements Chef and override the doCook() method in both component. And trying to autowire in VegChefService service.



public interface Chef {
String doCook();
}

@Component
public class VegChef implements Chef {
@Override
public String doCook() {
return "Vegetarian Food";
}
}

@Component
public class NonVegChef implements Chef {
@Override
public String doCook() {
return "Non-Vegetarian Food";
}
}

@Service
public class VegChefService {
@Autowired
private Chef chef;
}



 Here we will get the error says "Could not autowire. There is more than one bean of 'Chef' type.

Let see how to resolve the problem by using @Qualifier to indicate which bean want to use. we need add @Qualifier code in Component class like below, and need to add @Qualifier in service class to specify the bean name.

@Qualifier("Veg")
public class VegChef implements Chef {
@Override
public String doCook() {
return "Vegetarian Food";
}

} 


@Service
public class VegChefService {
@Autowired
@Qualifier("Veg")
private Chef chef;
}

As conclusion @Qualifier used to resolve more then one bean issue. 

Next topic @Primary Annotation

No comments:

Post a Comment