Autowiring interface with single implementation

In all my previous posts under Spring Core, I showed how to inject a bean belonging to a particular class.

But in reality, to maintain a loose coupling we program to an interface and not to a class. (Interface doesn’t represent Java Interface. Here Interface is generic term that represents either Java Interface
or Java Abstract Class).

In this post, I will show with example how to inject a bean based on an Interface type and not by Class type.

For our example, I will create a below interface

Interface

package package28;

public interface Dao {
}

Its corresponding implementation is as shown below

Class implementing the interface

package package28;

import org.springframework.stereotype.Component;

@Component
public class DBDao implements Dao {
}

Below is the main class

Main class

1  package package28;
2  
3  import org.springframework.beans.factory.annotation.Autowired;
4  import org.springframework.context.ApplicationContext;
5  import org.springframework.context.annotation.AnnotationConfigApplicationContext;
6  import org.springframework.context.annotation.ComponentScan;
7  import org.springframework.context.annotation.Configuration;
8  
9  @ComponentScan(basePackages = "package28")
10 public class Example28 {
11     @Autowired
12     private Dao dao;
13 
14     public void setDao(Dao dao) {
15         this.dao = dao;
16     }
17 
18     public Dao getDao() {
19         return this.dao;
20     }
21 
22     public static void main(String[] args) {
23         ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Example28.class);
24         Example28 example = applicationContext.getBean(Example28.class);
25         System.out.println(example.getDao());
26     }
27 }
28

In the above code, at line 12, I declared a field named “dao” of type “Dao” interface. We are not mentioning the class type here.

If I had to inject the bean based on class type. I would have declared like below

    @Autowired
    private DBDao dao;

Where “DBDao” is a class and not an interface.

Spring framework will automatically figure out the implementation class of this interface and inject it.

In this way we can inject a bean based on interface type and not on class type.

Leave a comment