Why do we need service layer?

后端 未结 5 1961
温柔的废话
温柔的废话 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:14

    Layered architectures are generally suypported by this contention:

    We use layers to allow us to abstract away the underlying implementation so we that we can easily change it.

    A happy side effect of layering is that - if followed faithfully - it can make the system more testable by (a) using interfaces to define each layer and (b) encouraging separation of concerns.

    So, that's the principle (briefly, at least) but like any principle it can be misunderstood and misapplied.

    While the benefits of layering to hide data access from the view layer (and vice versa) are solid in most cases, the benefits of including a service layer between the view layer and the data layer are not always so compelling. A system which has ...

    • A small number of controllers
    • A small number of repositories
    • A 1:1 mapping between controller and repository
    • No need for complex transformations between domain representations (for repositories) and view representations (for controllers)

    ... probably doesn't need a service layer.

    Whereas, a system which has ...

    • Large numbers of controller and repositories
    • Complex relationshiops betwen controllers and repositores e.g. maybe a controller uses multiple repositories and combines their results or invokes these repositories in a chain
    • Complex transformations between domain representations (for repositories) and view representations (for controllers)

    ... probably does need a service layer.

提交回复
热议问题