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
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.
The service layer consists of a collection of Java classes that implement business logic (data retrieval, updates, deletions, and so on) through one or more high-level methods. In other words, the service layer controls the workflow.
A service layer is an additional layer in an ASP.NET MVC application that mediates communication between a controller and repository layer. The service layer contains business logic. In particular, it contains validation logic. For example, the product service layer in Listing 3 has a CreateProduct() method.
In intelligent networks (IN) and cellular networks, service layer is a conceptual layer within a network service provider architecture. It aims at providing middleware that serves third-party value-added services and applications at a higher application layer.
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
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 ...
... probably doesn't need a service layer.
Whereas, a system which has ...
... probably does need a service layer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With