Autowiring — @Qualifier
Learn about the @Qualifier annotation for autowiring and compare it to @Primary.
We'll cover the following
@Qualifier
annotation
Like @Primary
, the @Qualifier
annotation gives priority to one bean over the other if two beans of the same type are found. The bean whose name is specified in the @Qualifier
annotation qualifies to be injected as a dependency. The @Qualifier
annotation can be used in a scenario when we have multiple objects of the same type and autowiring by name cannot be used because the variable name doesn’t match any bean name.
For the code example shown in this lesson, we have created a sub-package called
lesson6
inside the packageio.datajek.spring.basics.movierecommendersystem
.The package containsMovieRecommenderSystemApplication.java
,RecommenderImplementation.java
,Filter.java
,ContentBasedFilter.java
, andCollaborativeFilter.java
files from the previous lesson.Say, we want to use the name
CBF
forContentBasedFilter
. We can either specify it in the@Component
annotation or use@Qualifier
annotation on the class. Both approaches, shown below, yield the same result.
Here’s the first approach:
Level up your interview prep. Join Educative to access 80+ hands-on prep courses.