为什么大多数人创建接口是为了创建服务



我尝试直接通过类创建service,而无需实现自定义interface。它有效!所以我想知道为什么大多数人花时间创建一个界面来创建一个service

我可以指出两个原因:

  • 它有助于解耦。(当然,仍然可以在没有接口的情况下创建解耦类。

  • 您在问题标签中添加了 spring,因此这个原因是特定的:在许多情况下,Spring 需要一个接口来正确创建 jdk 代理(使用 AOP 时需要这样做(。可以在没有接口的情况下创建代理(spring将使用CGLIG而不是JDK(,但是"引擎盖下"存在一些差异。查看此处。

首先,我们使用服务层来包装一些业务逻辑到我们的应用程序中。

为了使我们的服务层从客户端更加抽象,我们将首先创建服务接口,其中包含一些类似于 CURD 存储库的抽象方法。

然后,我们需要通过创建像ServiceImplementation这样的新类,为服务接口中的抽象方法编写逻辑。

因此,控制流将是控制器到服务实现。

  class StudentController {
       ServiceImplementation serviceImpl;
   // Endpoints implementation.
    GET;
    POST;
    PUT;
    DELETE;
 }

接口服务 {

List<StudentInfo> getAllStudents();
StudentInfo addStudent(Student std);
StudentInfo updateStudent(Student student);
StudentInfo findStudentById(String id);
boolean deleteStudent(String id);

}

public class ServiceImplementation implements Service{
    private StudentRepository studentRepository;
   // Implement the abstract methods
}
public interface StudentRepository extends JpaRepository<Student, String>{
}

这是我们将遵循的标准模式。

最新更新