Spring MVC – Separation of logic RestController and Service

Tags: , , ,



I started using Spring MVC to build my first REST API 🙂 Now I struggle a bit of where to put which logic. I read the following: @RestController: Handles requests, defines the API the user can use @Service: Contains the business logic @Repository: Abstracts away from access to DB

In an easy first example, I saw the flow was like this: RestController calls Service, Service calls Repository. In the first step, I did it like this.

Now I want to use ResponseEntity – I hear it is good practice to use that. But now I start wondering: Should the service layer return ResponseEntity or just the instances of the domain model?

To show what I mean (yes, I am a big football fan):

@GetMapping("/clubs")
public ResponseEntity<List<FootballClub>> getAllClubs(@RequestParam String footballLeague) {
    List<FootballClub> clubs = service.getAllClubs(footballLeague);
    return new ResponseEntity(...);
}

Is it best practice to do it like this or to let the Service return the ResponseEntity? I am new to Spring MVC. I read some articles on Stackoverflow and some explain the general setup. But I could not find how to deal with for instance ResponseEntity.

I think you can argue that ResponseEntity should also be in Service as you might need to return method not allowed or something like this and determining whether to return a method not allowed ResponseEntity or an OK Entity could be considered part of the business logic. But I don’t know.

Thank you!

Answer

Short Answer

Yes, Service returning domain object should be preferable to a Service returning ResponseEntity<>.

Long Answer

There is no best practices. Having said that, you should think of implementing something like Hexagonal or Layered architecture. In Hexagonal architecture, application/domain logic is confined in application/domain layer which is separated from presentation, persistence/infrastructure layer. Interfaces are defined in application layers (called ports) and implementation is provided in infrastructure layer (called adapters). There is an excelled article on this.

Concepts like Service, Repository is taken from DDD. To know more about DDD you can check Vaughn Vernon book Implementing Domain-Driven Design.



Source: stackoverflow