Java 8 and Spring 4: using autwiring in an interface

Java 8 has added a new feature with which we can provide method implementation in interfaces. Is there a way in Spring 4 with which we can embed beans in an interface that can be used inside the method body? Below is a 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(); } } 
+7
java-8 spring-4
source share
1 answer

It's a bit complicated, but it works if you need a dependency inside the interface for any requirements.

The idea would be to declare a method that forces the implemented class to provide this dependency that you want to auto-increment.

The bad side of this approach is that if you want to provide too many dependencies, the code will not be very nice, 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; } } 
+7
source share

All Articles