What is the use of @Qualifier annotation in Spring?

Your thoughts?

|

Let's say you have two classes that implement the same type...

@Component
public class Pig implements Animal {
...
}

@Component
public class Cow implements Animal {
...
}

Let's say we want to autowire one of our animals...

public class myFarm {
@Autowired
Cow cow;
...
}

This works because we explicitly define Cow as the type. Spring Boot automatically knows what we are trying to inject...

public class MyFarm {
@Autowired
Animal Cow;
...
}

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...

public class MyFarm {
@Autowired
Animal animal;
...
}

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...

public class MyFarm {
@Autowired
@Qualifier('Cow')
Animal animal
...
}

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...

@Component('Cow')
public class Cow implements Animal {
...
}


|

@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 :)