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();
}
}
你不能实例化一个接口。你会如何在其中自动装入一个字段? – Tunaki
我想在我的方法体内使用spring管理的服务。一种方法是使用ApplicationContext.getbean(“)”方法,但我正在寻找Spring 4中的任何特性,我可以在接口中注入Spring管理的bean,接口将由一些bean实现,所以它应该可用于实现类默认情况下,因为接口的成员是静态最终的,所以我不能直接使用@autowiring –
DI在Spring中可以通过在构造函数(构造函数注入)中设置依赖关系,或者通过属性(setter注入)来工作。接口,你没有构造函数,也没有实例变量(你在界面声明的变量是'static final'),所以没有办法注入任何东西。 – Ruben