Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring boot - @Service class calling another @Service class

Is it fine to have a @Service annotated class calling another @Service annotated class? Or it is a bad practice?

Eg.:

@Service
public class MyService {

    // ...
    
    @Autowired
    private MyOtherService myOtherService;
    
    // ...

}

EDIT - after 3 years

It's ok to have dependencies from one service to another. This is mainly because of reusability. If circular dependencies happen between two services from the same module, that's ok.

You should only avoid circular dependencies between modules.

like image 405
Matheus Cirillo Avatar asked Aug 23 '18 14:08

Matheus Cirillo


People also ask

Can a service call another service spring boot?

Spring boot supports calling one rest service to another rest service using the RestTemplate class. RestTemplate is a synchronised client side class that is responsible for calling another rest service. RestTemplate supports all HTTP methods such as GET, POST, DELET, PUT, HEAD, etc.

Can a service call another service?

When calling a method, a service method may call another service call and that may also call another service method which can lead to circular call again.

Can we use @component and @service in same class?

tl;dr: Use @Component or @Service on both, and there's no significant difference between them ( @Component is becoming more usual because of that).


2 Answers

It is not any restriction calling a service from another one. Unless you make circular dependency between services.

Circular dependency : https://en.wikipedia.org/wiki/Circular_dependency

Circular dependency in spring : https://www.baeldung.com/circular-dependencies-in-spring

like image 158
Emre Savcı Avatar answered Oct 20 '22 16:10

Emre Savcı


Its good practice since utility class are being ignored these days, approach getting motivated by horizontal scaling... Surely services got to interact with other.

No need to worry, its like one service manager needs services of another manager.

just only one should be dependent on other, not both.

like image 28
Rohit Kumar Avatar answered Oct 20 '22 15:10

Rohit Kumar