Java 8和Spring 4:在界面中使用自动装配 [英] Java 8 and Spring 4 : Use autowiring in interface
问题描述
Java 8添加了一个新功能,通过它我们可以在接口中提供方法实现。
在Spring 4中是否有任何方法可以在接口中注入bean,可以在方法体内使用?
下面是示例代码
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();
}
}
推荐答案
这有点棘手,但如果您需要接口内的依赖项以满足任何要求,它就可以工作。
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.
这种方法的不好的一面是,如果你想提供太多的依赖项,代码将不会很好,因为每个依赖项需要一个getter。
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;
}
}
这篇关于Java 8和Spring 4:在界面中使用自动装配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!