I am pretty new working with the MVC pattern (Spring MVC). I have a very simple question. Can a service have a dependency on another service? something like:
@Service
public class MyFirstService{
.....
@Autowired
private MySecondService secondService;
......
}
Is this a "good practice" or is something that should be avoided?
Thanks!
Services can have dependencies on other services. A service that other services depend on is called an antecedent service. A dependent service depends on the antecedent service to be running so that the dependent service can function properly.
It is perfectly fine to have a service calling another service if that business code defined in the method is the same business functionality needed by the other service.
It is not any restriction calling a service from another one. Unless you make circular dependency between services.
Another approach would be to create a new service with dependencies on both AgreementService and OrganisationService, and have that new service carry out the responsibility. The new service would of course be injected into your controller.
There is a simple answer: yes.
One service depending on another service makes sense. Else it is possible that you have code duplications.
One example that comes into mind is having an EmailService
. I don't want to write email sending code several times so that I create a service out of this. This service would be called by other services naturally.
Yes. the expectation of service layer is to implement business logics of the application. assume that one business logic (implemented in one service) may need to use other service to do its operations. for example, LoanService module may access the InterestService to calculate the interest of the loan.
@Service
public class LoanService{
.....
@Autowired
private InterestService interestService;
......
}
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