In this post under Spring Core, I will explain with example how to autowire beans based on names instead of bean type.
Till now in all our previous posts, beans to be injected were figured out by the class type.
Sometimes there exist a situation where when Spring framework tries autowire a bean of a particular type and it finds two candidates that satisfies the requirement, Spring gets confused.
Consider the below example
1 package package27;
2
3 import org.springframework.beans.factory.annotation.Autowired;
4 import org.springframework.beans.factory.annotation.Qualifier;
5 import org.springframework.context.ApplicationContext;
6 import org.springframework.context.annotation.AnnotationConfigApplicationContext;
7 import org.springframework.context.annotation.Bean;
8 import org.springframework.context.annotation.Configuration;
9
10 @Configuration
11 public class Example27 {
12 @Autowired
13 private Dao dao;
14
15 @Bean
16 public Dao jmsDao() {
17 return new Dao("jmsDao");
18 }
19
20 @Bean
21 public Dao dbDao() {
22 return new Dao("dbDao");
23 }
24
25 public Dao getDao() {
26 return this.dao;
27 }
28
29 public static void main(String[] args) {
30 ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Example27.class);
31 Example27 example = applicationContext.getBean(Example27.class);
32 System.out.println(example.getDao());
33 }
34 }
In the above code, we are telling Spring to inject a bean for “dao” field whose class type is “Dao”.
Now based on the class type, we have two candidates “jmsDao” and “dbDao”.
Spring framework is unable to decide which one to pick.
That’s where “@Qualifier” annotation comes into picture.
It takes the bean name as an argument and it tells Spring framework to decide based on bean name and not bean type.
In our above code, we will make the below change
@Autowired
@Qualifier("dbDao")
private Dao dao;
We have applied “@Qualifier” annotation and passed “dbDao” name as an argument.
This is telling Spring framework to inject a bean whose name is “dbDao”.
In this way, we can autowire based on name instead of type using “@Qualifier” annotation.