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

Categories

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

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

1 Answer

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...