Sub topic 3
Keeping Controllers Thin with a Service Layer
Assume Java fundamentals, Spring Boot dependency injection, HTTP methods, and Maven or Gradle. This chapter focuses on the web layer rather than database code.
Delegate business logic to a service
A controller should translate HTTP requests into application calls. A service contains business rules and coordinates repositories or other services. This separation makes both layers easier to test.
@RestController
@RequestMapping("/api/books")
class BookController {
private final BookService service;
BookController(BookService service) {
this.service = service;
}
@GetMapping
List<BookResponse> list(Pageable pageable) {
return service.list(pageable);
}
@PostMapping
ResponseEntity<BookResponse> create(
@Valid @RequestBody CreateBookRequest request) {
BookResponse book = service.create(request);
URI location = URI.create("/api/books/" + book.id());
return ResponseEntity.created(location).body(book);
}
}
interface BookService {
List<BookResponse> list(Pageable pageable);
BookResponse create(CreateBookRequest request);
}Validate input with `@Valid`
A data transfer object (DTO) carries data across the HTTP boundary. Bean Validation annotations describe acceptable input. @Valid tells Spring to check the request body before calling the method.
public record CreateBookRequest(
@NotBlank @Size(max = 200) String title,
@NotBlank String author) {}Add the validation starter to the project. Invalid input normally produces a 400 Bad Request.
> callout note > Validate at the boundary, but keep important business rules in the service. A request annotation cannot replace domain checks.
Handle errors consistently
Throw a meaningful exception when the service cannot find a resource. @RestControllerAdvice handles that exception for every controller.
@RestControllerAdvice
class ApiExceptionHandler {
@ExceptionHandler(BookNotFoundException.class)
ProblemDetail notFound(BookNotFoundException ex) {
ProblemDetail problem = ProblemDetail.forStatusAndDetail(
HttpStatus.NOT_FOUND, ex.getMessage());
problem.setTitle("Book not found");
return problem;
}
}ProblemDetail follows the standardized problem-details format. Enable Spring MVC's built-in problem responses with spring.mvc.problemdetails.enabled=true.
Paginate, sort, and negotiate content
Use Pageable for page number, size, and sorting. For example, ?page=0&size=20&sort=title,asc lets the client control collection order within configured limits.
Content negotiation chooses a representation from the Accept header. Use produces when an endpoint supports a specific media type.
@GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
List<BookResponse> list(Pageable pageable) {
return service.list(pageable);
}Test the web layer
@WebMvcTest loads MVC components without the full application. Mock the service, then use MockMvc to send requests and verify HTTP behavior.
@WebMvcTest(BookController.class)
class BookControllerTest {
@Autowired MockMvc mvc;
@MockitoBean BookService service;
@Test
void getsBook() throws Exception {
when(service.get(1L))
.thenReturn(new BookResponse(1L, "Dune", "Frank Herbert"));
mvc.perform(get("/api/books/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.title").value("Dune"));
}
}@MockitoBean is available in Spring Boot 3.4 and later. Earlier versions use @MockBean.
Exercise
Where should a rule such as “a title must be unique” normally be enforced?
Show answer
In the service or domain layer, because it is a business rule. The controller should only validate request shape and delegate the operation.