Spring controller as a single business resource

The Spring Framework is great in how it provides an opinionated way to structure our applications, and because so many people are using it, it’s easy for new developers to quickly familiarise themselves with the codebase.

Despite the technical conformity across codebases, there is a lot of developer discretion in structuring it to best meet the organizational context the application is intended for. One guideline I’ve started using for the controllers that handle HTTP requests is to keep one controller representative of one business resource. This is made easy if we design our URLs as a resource (e.g. POST http://www.example.com/books) instead of as a remote procedure call (e.g. POST http://www.example.com/create-book). If structured like this, the BookController would then represent a Book business resource, with the associated CRUD operations to handle that resource, and nothing more.

@RestController@RequestMapping("/books")
public class BookController {    
  @PostMapping    
  public ResponseEntity createNewBook(@RequestBody BookRequest bookRequest) {
        // Logic to handle creation of books        
  }        

  @GetMapping    
  public List getAllBooks() {
        // Logic to get all the books    
  }        

  @GetMapping("/{identifier}")    
  public BookResponse getIndividualBook(@PathVariable String identifier) {
        // Logic to get individual book    
  }        

  @DeleteMapping("/{identifier}")    
  public BookResponse deleteBook(@PathVariable String identifier) {
        // Logic to delete book    
  }
}

Structuring it as so, with several micro-controllers instead of one giant controller that handles multiple resources, helps when writing maintainable and readable tests for the controller, and keeps the production code more maintainable and easier to change over time (in my opinion).

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s