Reputation: 43
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?
Upvotes: 2
Views: 11157
Reputation: 1886
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. Roughly this dictates that classes should have a single responsibility and reason to change, 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.
Upvotes: 4
Reputation: 1592
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
@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.Upvotes: 2