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
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.
Thats a way to separate service functionality from transport, your service defines a functionality that cover a single responsability (SOLID), and that can be exposed using different ports (Hexagonal Architecture), for example HTTP/REST or AMQP.
Adding a service layer give you the flexibility to change your port in the future, or use more than one.
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
The Spring boot controller is an interface to the outside world, not much different than a UI for example. Just like you want to be able to have more than one UI flavour, you might more than one interface to your business logic. Especially if you want it to be long lived and adaptable to future API frameworks. If your logic was embedded in the controller, you have to do quite some refactoring when you arrive at that point.
So the need of a separate controller depends on the complexity of your logic.
It is like this so you don't have to put a lot of code inside the RestController layer, which should be clean and only with code related to communications.
So all the logic and the IFs etc. should stay in the Controller layer.
The Repository layer should stick to the interfacing way, which should not have any code inside the methods, but only the layout of how the data is obtained, but not its logic.