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 bean 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 dependencies as follows:

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 value of the Table object will be “123456”.

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

Using @Qualifier annotation in Spring
Đánh giá bài viết
Chia sẽ bài viết này ...Share on Facebook
4Tweet about this on Twitter
Share on LinkedIn

Add Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.