Why do we need service layer?

后端 未结 5 1956
温柔的废话
温柔的废话 2020-12-14 20:49

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

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-14 21:21

    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.

    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.

提交回复
热议问题