Autowiring By Type — @Primary

Learn how Spring dynamically autowires a dependency in case it finds more than one component of the same type.

Dynamic bean selection

In the last lesson, we saw Spring manage two beans of the RecommenderImplementation and ContentBasedFilter classes for us. In this lesson, we will add another bean and see how Spring can dynamically choose a bean if it finds two matches of the same type.

For the code example shown in this lesson, we have created a sub-package called lesson4 inside the package io.datajek.spring.basics.movierecommendersystem.

The package contains MovieRecommenderSystemApplication.java, RecommenderImplementation.java, ContentBasedFilter.java, and CollaborativeFilter.java files from the previous lesson.

We will add the @Component annotation on the CollaborativeFilter class to declare it a bean. Now both implementations of the Filter interface are beans. Previously, when Spring searched for a dependency to be autowired in the RecommenderImplementation object, it only found one bean of matching type. Now when we run the application, it fails to start.

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.