2015-10-15 75 views
7

Java 8添加了一项新功能,通过该功能我们可以在接口中提供方法实现。 在Spring 4中有什么方法可以在可以在方法体内部使用的接口中注入bean? 下面是示例代码Java 8和Spring 4:在界面中使用自动装配

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(); 
} 
} 
+3

你不能实例化一个接口。你会如何在其中自动装入一个字段? – Tunaki

+0

我想在我的方法体内使用spring管理的服务。一种方法是使用ApplicationContext.getbean(“)”方法,但我正在寻找Spring 4中的任何特性,我可以在接口中注入Spring管理的bean,接口将由一些bean实现,所以它应该可用于实现类默认情况下,因为接口的成员是静态最终的,所以我不能直接使用@autowiring –

+0

DI在Spring中可以通过在构造函数(构造函数注入)中设置依赖关系,或者通过属性(setter注入)来工作。接口,你没有构造函数,也没有实例变量(你在界面声明的变量是'static final'),所以没有办法注入任何东西。 – Ruben

回答

7

这是一个有点棘手,但它的工作原理,如果你需要的任何需求的接口内的依赖性。

这个想法是声明一个方法,它将强制实现的类提供您想要自动装配的依赖关系。

这种方法的坏处是,如果你想提供太多的依赖关系,代码将不会很漂亮,因为每个依赖关系都需要一个getter。

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; 
    } 

}