【发布时间】:2016-01-13 22:08:25
【问题描述】:
Java 8 添加了一个新特性,通过它我们可以在接口中提供方法实现。 在 Spring 4 中有什么方法可以在接口中注入可以在方法体内部使用的 bean? 下面是示例代码
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();
}
}
【问题讨论】:
-
你不能实例化一个接口。你将如何在其中自动装配一个字段?
-
我想在我的方法体内使用 Spring 托管服务。一种方法是使用 ApplicationContext.getbean("
) 方法。但我正在寻找 Spring 4 中的任何功能,我可以利用这些功能在接口中注入 Spring 托管 bean。接口将由某个 bean 实现。所以它应该在实现类中可用。默认情况下,由于接口的成员是静态最终的,所以我不能直接使用@autowiring。 -
Spring 中的 DI 通过在构造函数中设置依赖项(构造函数注入)或通过属性(setter 注入)来工作。在接口中,你没有构造函数,也没有实例变量(你在接口中声明的变量是
static final),所以没有办法注入任何东西。 -
你不能为此使用抽象类吗?
-
一个可能的用例可以在实现 CRUD 存储库的 Spring Data 接口中。我正在用 Mysql 测试新的 Spring R2DBC。因此,像通常的 Spring Data Interfaces 一样,如果不提供实现,就无法编写自定义抽象方法,如 findByIdLike 和其他自定义查询。在这种情况下,我需要使用数据库客户端并使用实现编写自定义方法,可能使用新的 Java 8 默认方法。我不想编写新的接口和实现类,因为 Spring 和我的接口都将与同一个实体/表进行交互。