Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
969 views
in Technique[技术] by (71.8m points)

spring - Why do we need service layer?

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?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...