Autowiring By Name

Autowiring by Name is an approach, while creating an bean, the dependency is injected by matching the name of the reference variable to the bean name. This means that the developer has to ensure that the variable name is the same as its bean.

We have another way to do the autowiring, this is called by Name, we can use it along with the autowiring by Type, but what will happen when Spring founds both autowiring types?, let’s review it.

In the last entry Autowiring by type primary we looked the autowiring by Type and the priority that gives the @Primary annotation. As we mention we have another autowiring called By Name, in this we specify the bean that is to be used by name. In this approach, while creating an bean, the dependency is injected by matching the name of the reference variable to the bean name. This means that the developer has to ensure that the variable name is the same as its bean.

For this example, we added a new package called byname in com.programmingsquirrel.coffeeshop, also we copy all the code that we have in com.programmingsquirrel.coffeeshop.primary including the subpackage impl and their content.

First, eliminate the @Primary annotation in the LatteCoffee and MochaCoffee classes.

[gist https://gist.github.com/CesarPasillas/63b41cdcd5986e2e91081c0dc9fe5800]

[gist https://gist.github.com/CesarPasillas/8dc3d4814e5d2646984ed73605a1e5b5]

Then we need to go to the MakeCoffeeImplementation class and change the name of the field Coffee with the name of the bean that we need to have injected, using the the camelCase, in this case will use the LatteCoffee bean, so will change coffee to latteCoffee.

[gist https://gist.github.com/CesarPasillas/2f8b82892fe7a31240605a66eff6098d]

Just remember if you want to use this autowiring you need to use the bean name in the field where is needed. if you miss spell the name or use another name the autowiring will not be performed because Spring know that we have two beans and again SPring don’t know which one to use give un an NoUniqueBeanDefinitionException.

Precedence by Name and by Type

Until now we review two autowire types, by Name and By Type, but what happens if we use both, which one has precedence, so let’s add again the @Primary annotation into the MochaCoffee class.

[gist https://gist.github.com/CesarPasillas/82e2a682eee8697fef37d5695066cb7e]

Then we run the CoffeeshopApplication app and if we review the output console we will have the results of the MochaCoffee.

Making a Mocha…
The Coffee is ready

This means that @Primary has precedence for Spring than the autowiring by Name.

Remember that you can download the code from CoffeShop

Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *