Autowiring — @Qualifier

Learn about the @Qualifier annotation for autowiring and compare it to @Primary.

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

  1. For the code example shown in this lesson, we have created a sub-package called lesson6 inside the package io.datajek.spring.basics.movierecommendersystem.The package contains MovieRecommenderSystemApplication.java, RecommenderImplementation.java, Filter.java, ContentBasedFilter.java, and CollaborativeFilter.java files from the previous lesson.

  2. Say, we want to use the name CBF for ContentBasedFilter. 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 70+ hands-on prep courses.