Using @Qualifier annotation in Spring

In the tutorial on Bean autowiring in Spring framework, you know in the case of byType autowire, we cannot declare more than one bean of the same dependency in Spring’s container. Because in this case, Spring does not know what bean to use for autowire.

Is there any solution when we need to declare multiple beans for the same object but still autowire? Fortunately, we still have one way, that is, you move to autowire bean using the @Autowired annotation and use the @Qualifier annotation that Spring supports for us. Let’s see what we need to do!

For easy visualization, I will create an example as follows:

Using @Qualifier annotation in Spring

With Spring dependency as follows:

I will use Java 17 for this example:

Room class:

Table class

Application class

And declare the Table and Room objects in the Spring configuration file:

OK, now we can start!

As you all know, if we now declare more than one bean for the same Table object in our example as follows:

When we run, we get an error:

To resolve this error, we will use the @Qualifier annotation to specify which bean of the Table object will be autowire into the bean of the Room object by editing the Room class as follows:

The value in the @Qualifier annotation is the bean id of the bean that we need autowire. Here, I use bean id “table1”, which means that the value of the code attribute of the Table object will be “123456”.

Now, rerun the example, you will get the following results:

Add Comment