What is the use of @Qualifier annotation in Spring?
WhoDemyUdemy
Last updated on
Your thoughts?
Share your thoughts
@Qualifier annotation must be specified when using @Autowired with injected bean having same type across multiple managed beans.
The use of @Qualifier is to qualify your beans :)
Let's say you have two classes that implement the same type...
Let's say we want to autowire one of our animals...
This works because we explicitly define Cow as the type. Spring Boot automatically knows what we are trying to inject...
This also works because our field name matches the type Cow. This is some Spring Boot magic that allows us to not specify which bean we are talking about...
This DOES NOT work. This is because Spring checks for which bean to inject by type. Since both Cow and Pig are Spring managed beans having the same type, you will get an Exception when running the application...
@Qualifier to the rescue...
This works. The @Qualifier annotation differentiates so Spring knows to inject an instance of Cow.
Note that you also need to do something like this for @Qualifier to get the naming right...