Java 8 and Spring 4 : Use autowiring in interface

Ashish Shukla picture Ashish Shukla · Oct 15, 2015 · Viewed 25.5k times · Source

Java 8 added a new feature by which we can provide method implementation in interfaces. Is there any way in Spring 4 by which we can inject beans in the interface which can be used inside the method body? Below is the sample code

public interface TestWiring{

@Autowired
public Service service;// this is not possible as it would be static.
//Is there any way I can inject any service bean which can be used inside testWiringMethod.
default void testWiringMethod(){
  // Call method of service
  service.testService();
 }
}

Answer

ibai picture ibai · Jul 4, 2016

This is a bit tricky but it works if you need the dependency inside the interface for whatever requirement.

The idea would be to declare a method that will force the implemented class to provide that dependency you want to autowire.

The bad side of this approach is that if you want to provide too many dependencies the code won't be pretty since you will need one getter for each dependency.

public interface TestWiring {

   public Service getService();

   default void testWiringMethod(){
       getService().testService();
   }

}


public class TestClass implements TestWiring {

    @Autowire private Service service;

    @Override
    public Service getService() {
        return service;
    }

}