【问题标题】:Why create an interface for a service class? [duplicate]为什么要为服务类创建接口? [复制]
【发布时间】:2021-08-09 11:38:23
【问题描述】:

使用Spring框架,习惯上创建一个服务来创建一个定义服务主要方法的接口。

interface MultiplicationService {
    long execute(int a, int b);
}

class MultiplicationServiceImpl implements MultiplicationService {
    // implementation
}

创建界面有什么意义?

【问题讨论】:

    标签: java spring spring-boot service


    【解决方案1】:

    为任何类创建接口的目的是将 API 与实现分开。目标是在不影响客户端的情况下更改实现。

    您可以在 JDK 本身中找到大量示例:

    1. Collections API 有多个 List 接口的实现。
    2. JDBC 是全接口,允许您更改关系数据库供应商而无需重写代码。

    Spring 也可以轻松地为接口生成代理字节码 - 对于 AOP、事务管理器等很有用。

    【讨论】:

    • 如果您已经确定问题是重复的,为什么还要回答它?
    • 先给出答案。
    猜你喜欢
    • 1970-01-01
    • 2011-05-09
    • 1970-01-01
    • 2020-05-14
    • 1970-01-01
    • 2012-02-15
    • 2015-07-11
    • 1970-01-01
    • 2012-03-16
    相关资源
    最近更新 更多