Autowiring interface with multiple implementation

Autowiring interface with multiple implementation

In this post, I will explain with example how to inject a bean whose type is an interface (Java Interface or Abstract class) and it has multiple classes that implements it.

In the previous post, I showed how Spring Framework inject a bean whose type is an interface and has single implementation class.

In that case, the Spring framework was able automatically figure out the class whose instance it has to create and inject to bean of interface type.

But in reality, there will not always be a single implementation for an interface. They can be many and in that case Spring framework cannot decide which implementation class’s instance be created
and injected into the bean.

To solve this we use “@Qualifier” annotation.

We annotate the field which has to be autowired with “@Qualifier” annotation and pass the implementation class bean name as an argument.

Lets take an example. I have created a interface below

Interface

package package29;

public interface Dao {
}

They are two class that implement the above interface as mentioed below

JMSDao

package package29;

import org.springframework.stereotype.Component;

@Component("jmsDao")
public class JMSDao implements Dao {
}

DBDao

package package29;

import org.springframework.stereotype.Component;

@Component("dbDao")
public class DBDao implements Dao {
}

Below is the main code for your reference

Main class

1  package package29;
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.ComponentScan;
8  
9  @ComponentScan(basePackages = "package29")
10 public class Example29 {
11     @Autowired
12     @Qualifier("jmsDao")
13     private Dao dao;
14 
15     public Dao getDao() {
16         return dao;
17     }
18 
19     public void setDao(Dao dao) {
20         this.dao = dao;
21     }
22 
23     public static void main(String[] args) {
24         ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Example29.class);
25         Example29 example = applicationContext.getBean(Example29.class);
26         System.out.println(example.getDao());
27     }
28 }

In the above code, at line 13, I created a field named “dao” of type “Dao” interface.

I annotated the field with “@Autowired” annotation to instruct the Spring framework to inject a bean for this property.

I also annotated the field with “@Qualifier” annotation instructing the Spring framework to create an instance of a bean named “jmsDao” and inject it to “dao” field.

As a result, the instance of “JMSDao” is created and assigned to that field.

In this way, we can autowire field of interface type having multiple implementation class.

Leave a comment