I've just read the articles below
here: What is the best approach to use multiple services inside a resource controller?
and here: Can I have multiple services in a Controller class - Spring MVC?
the article said that I shouldn't call multiple services in a Controller class. I should encapsulate all services in a Facade class (Facade pattern).
So Why shouldn't I call multiple services in a Controller class?
And Can I call multiple service in a Service class? Is it correct?
CodePudding user response:
Technically there is nothing that prevents you from calling multiple services from your controller, but it is probably a bad design decision, mainly due to the Single Responsibility Principle. Classes should do one thing, and do that one thing good, controllers are the interface of your application and should focus on being only that. Any class that needs to import multiple services probably contain some business logic and that code is probably better placed in separate business layer classes than the controller class.
If you only use a single service in each metod of your controller maybe you should split the controller into smaller controllers that each use the service that is relevant for each of them.
CodePudding user response:
Traditionally, when we talk about MVC pattern, the job of the controller is to take care of the Business Logic. However, when we actually implement it, the controller may end up with some validation routine calls, setting model attributes and view (not required in Rest controller) etc.
The design pattern to have Service layer and persistence layer evolved from the same need to separate all this logic from presentation layer. So, accordingly, all the business logic shall go in Service layer and persistence logic in persistence layer.
Calls to multiple services in Controller is definitely acceptable but then there are aspects like
- Reusability: If you encapsulate the logic of multiple service calls using Facade pattern at service layer, you increase the chance of reusing that code somewhere else. With all the logic in Controller method, you can't reuse it.
- Transactions: When you have transactions, to mark the transaction boundaries, it makes more sense to encapsulate the logic at service layer, and mark the method as
@Transactional
. You can certainly manage Transaction from Controller using annotation but then to handle scenarios like you want to rollback the transaction but at the same time Save the error data, you will have to manage it programmatically.