为什么需要服务层? [英] Why do we need service layer?

查看:157
本文介绍了为什么需要服务层?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在学习Spring Boot,我已经看到人们如何创建控制器,注入服务类以及在服务类中注入存储库.

I'm currently learning Spring Boot and I've seen how people create a controller, inject the service class and in the service class inject the repository.

为什么我们需要服务类作为中间人,为什么我们不能只是将存储库注入到控制器中?

Why do we need the service class as a middleman and why can't we just inject the repository into controller?

这是使我感到困惑的教程: https://www.youtube .com/watch?v = lpcOSXWPXTk& list = PLqq-6Pq4lTTbx8p2oCgcAQGQyqN8XeA1x

Here's the tutorial that confused me: https://www.youtube.com/watch?v=lpcOSXWPXTk&list=PLqq-6Pq4lTTbx8p2oCgcAQGQyqN8XeA1x

推荐答案

您并不总是需要服务层.尤其是如果您的API仅是简单的CRUD操作,例如,不需要实际逻辑或计算.

You don't always need a service layer. Especially if your APIs are just simple CRUD operations, for example, with no real logic required or calculations.

但是,如果您有一个在查询存储库之前执行一些逻辑的API,则应在单独的服务类中.这是一种良好的做法,是由所谓的单一责任原则引起的.

However, if you have an API which performs some logic before querying your repository then this should be in a separate service class. This is good practice arising from what is known as the single responsibility principle.

https://en.wikipedia.org/wiki/Single_responsibility_principle

  • 您的财务负责人的唯一责任是处理 传入请求.
  • 服务层的唯一职责是对控制器接收到的数据进行所需的任何逻辑.
  • 存储库的唯一职责是查询数据库.
  • Your Controller's single responsibility should be to handle the incoming request.
  • The Service layer's single responsibility is to do any logic required with the data received by the Controller.
  • The repository's single responsibility is to query the data base.

这篇关于为什么需要服务层?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆