Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
913 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 Reply

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...