Autowiring By Name
Learn about the autowiring by name and see which approach has higher priority, by name or by type.
We'll cover the following
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
For the code example shown in this lesson, we have created a sub-package called
lesson5
inside the packageio.datajek.spring.basics.movierecommendersystem
.The package containsMovieRecommenderSystemApplication.java
,RecommenderImplementation.java
,Filter.java
,ContentBasedFilter.java
, andCollaborativeFilter.java
files from the previous lesson.We will begin by omitting the
@Primary
annotation from theCollaborativeFilter
class. Now, to let Spring know which bean to use, we will change the variable name in theRecommenderImplementation
class to match the bean name as follows:
Get hands-on with 1400+ tech skills courses.