Autowiring By Name

Learn about the autowiring by name and see which approach has higher priority, by name or by type.

Autowiring by name in Spring

In the last lesson, we looked at the autowiring by type approach where priority was given to the collaborative filter using the @Primary annotation.

Another approach is autowiring by name where we specify the bean that is to be used by name. In this approach, while creating an object, the dependency is injected by matching the name of the reference variable to the bean name. The developer has to ensure that the variable name is the same as its bean name.

Implementation

  1. For the code example shown in this lesson, we have created a sub-package called lesson5 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. We will begin by omitting the @Primary annotation from the CollaborativeFilter class. Now, to let Spring know which bean to use, we will change the variable name in the RecommenderImplementation class to match the bean name as follows:

Get hands-on with 1400+ tech skills courses.