Sub topic 9
Keeping Controllers Thin with a Service Layer
This chapter assumes you know Java classes and records, basic dependency injection, and the controller annotations from earlier chapters. It shows where business logic belongs and why.
What a controller should do
A controller is an adapter between HTTP and your application. It has three jobs:
- Read the request: path variables, query parameters, and the body.
- Call one method on a service.
- Turn the result into a response: status code, headers, and body.
Everything else is business logic. Examples are searching, checking rules, generating IDs, and talking to a database. That work belongs in a service, a plain Spring bean marked with @Service.
A service for the book API
The controller from the earlier chapters calls service.search, service.get, and service.create. Here is a service that provides them. It keeps books in memory so the example runs without a database.
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.stereotype.Service;
@Service
public class BookService {
private final Map<Long, BookResponse> books = new ConcurrentHashMap<>();
private final AtomicLong nextId = new AtomicLong(1);
public List<BookResponse> search(String title) {
String needle = title.toLowerCase();
return books.values().stream()
.filter(b -> b.title().toLowerCase().contains(needle))
.sorted((a, b) -> Long.compare(a.id(), b.id()))
.toList();
}
public BookResponse get(long id) {
BookResponse book = books.get(id);
if (book == null) {
throw new BookNotFoundException(id);
}
return book;
}
public BookResponse create(CreateBookRequest request) {
long id = nextId.getAndIncrement();
BookResponse book = new BookResponse(id, request.title(), request.author());
books.put(id, book);
return book;
}
}The service throws BookNotFoundException, a domain exception. It does not know about HTTP. The @RestControllerAdvice from the error-handling chapter maps that exception to a 404 response.
Wiring the service into the controller
Spring creates one BookService bean. The controller receives it through its constructor.
@RestController
@RequestMapping("/api/books")
public class BookController {
private final BookService service;
public BookController(BookService service) {
this.service = service;
}
@GetMapping("/{id}")
public BookResponse get(@PathVariable long id) {
return service.get(id);
}
}With a single constructor, Spring needs no @Autowired. Declare the field final so the controller cannot be built without its service.
Common mistakes
- Business rules in the controller. If a controller method has loops,
ifchains about domain rules, or repository calls, move that code to the service. The rule is then reusable and testable without HTTP. - Passing HTTP types into the service. Keep
HttpServletRequest,ResponseEntity, andHttpStatusout of service signatures. A service that returnsResponseEntityis tied to the web layer. - Returning entities directly. Return DTOs such as
BookResponse. Exposing persistence entities leaks internal fields and couples your API to your database schema. - Catching exceptions in the controller. Let domain exceptions propagate. One central handler keeps error responses consistent.
Why it pays off
A thin controller needs few tests, because it only maps HTTP to a method call. In the testing chapter you will use @WebMvcTest and mock BookService. That works because the controller depends only on the service's public methods. The service's rules can be tested with plain unit tests, with no Spring context.
Exercise
A controller method for POST /api/books checks whether the author name is on a blocked list. If it is, the method builds a ResponseEntity with status 422. Which part belongs in the service, and which part stays in the controller?
Show answer
The blocked-list check belongs in the service. The service should throw a domain exception when the author is blocked. A @RestControllerAdvice handler maps that exception to status 422. The controller only passes the request to the service and returns the created response with its 201 status and Location header.