What is Qualifier in Spring Boot?

Your thoughts?

|

We all love to use @Autowired in Spring...

public class MyService {
    @Autowired
    User user
    ...
}

With @Autowired, Spring can automagically inject a Spring managed bean into the class when it initializes it.

Since Spring identifies which bean to inject via type, you can run into issues when you have multiple beans having the same type...

@Component
public class Admin implements User {
...
}

@Component
public class Influencer implements User {
...
}

In this scenario, Spring will throw an error because it doesn't know which kind of User to inject or autowire into the MyService class.

This is where @Qualifier comes into play...

@Component("Admin")
public class Admin implements User {
...
}

@Component
@Qualifier("Influencer")
public class Influencer implements User {
...
}


public class MyService {
    @Autowired
    @Qualifier("Admin")
    User user
    ...
}

By using @Qualifier, we can easily tell Spring which bean we are talking about....

For a detailed overview with examples, be sure to check out the official @Qualifier example using Spring Boot.

|

Lets say you have two @Components that implement the same interface...

@Component
public class Bedroom implements Room {
...
}

@Component
public class Bathroom implements Room {
...
}

and lets say you have a service that injects a Spring Bean of type "Room"...

public class House {
@Autowired
Room room;
...
}

You're going to have issues because Spring doesn't know which type of "Room" you are talking about...

This is where @Qualifying comes into play...

@Component("Bedroom")
public class Bedroom implements Room {
...
}

Then in the class where you will be autowiring...

@Autowired
@Qualifier("Bedroom")
Room room;
|

The @Qualifier annotation helps you "qualify" which bean to inject into a service.

This annotation is only necessary when you are using @Autowired

|

Qualifier is how you tell the application context what it should be caring about.

|

Spring loads all of the classes it cares about into the application context.

The application context magically injects beans into other beans with things like @Autowired

When multiple beans have the same type, then the application context can get a bit confused on which bean to inject or autowire into a class.

@Qualifier helps distinguish this when it's an issue...