Sub topic 9
Keeping controllers thin with a service layer
A controller should translate HTTP into Java calls and Java results back into HTTP. Business rules, data access, and transaction handling belong in a service layer. This chapter shows how to split the two, why the split pays off, and which mistakes to avoid.
This chapter assumes you know Java classes, interfaces and records, you have a Spring Boot web project, and you understand constructor injection. You have already seen @RestController, @GetMapping, @PathVariable, and @RequestBody.
Why separate the controller from the service
A controller method sits at the boundary between HTTP and your application. Its natural concerns are:
- Choosing the URL and HTTP method.
- Binding path variables, query parameters, and the JSON body to arguments.
- Triggering validation.
- Choosing the status code and headers of the response.
Everything else is application logic: deciding whether a title is a duplicate, calculating a price, or loading a record and failing if it is missing. If that logic lives in the controller, three problems appear.
- Reuse is hard. A scheduled job, a message listener, or a second controller cannot call a method that is tangled up with
ResponseEntityand request objects. - Tests are heavy. Every rule has to be tested through simulated HTTP, even when the rule has nothing to do with HTTP.
- Transactions are awkward. Transaction boundaries should wrap a unit of business work, not a web request.
A service is a plain Spring bean that knows nothing about HTTP. It takes ordinary arguments, returns ordinary objects, and signals failure with domain exceptions.
A minimal service
The controller from earlier chapters depends on a BookService. Here is one implementation. It keeps books in memory so you can run it without a database. The same shape works with a Spring Data repository.
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.stereotype.Service;
public record CreateBookRequest(String title, String author) {}
public record BookResponse(long id, String title, String author) {}
public class BookNotFoundException extends RuntimeException {
public BookNotFoundException(long id) {
super("No book with id " + id);
}
}
@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 created = new BookResponse(id, request.title(), request.author());
books.put(id, created);
return created;
}
}In a real project each public type lives in its own file. They are shown together here so the example is complete.
Notice what the service does not import: no ResponseEntity, no HttpStatus, no HttpServletRequest. When a book is missing, it throws BookNotFoundException. It does not decide that the answer is a 404. That decision belongs to the exception handler, which you built in the error-handling chapter.
The thin controller
With the service in place, each controller method has one job and is usually one to five lines long.
@RestController
@RequestMapping("/api/books")
public class BookController {
private final BookService service;
public BookController(BookService service) {
this.service = service;
}
@GetMapping
public List<BookResponse> list(@RequestParam(defaultValue = "") String title) {
return service.search(title);
}
@GetMapping("/{id}")
public BookResponse get(@PathVariable long id) {
return service.get(id);
}
@PostMapping
public ResponseEntity<BookResponse> create(@Valid @RequestBody CreateBookRequest request) {
BookResponse created = service.create(request);
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(created.id())
.toUri();
return ResponseEntity.created(location).body(created);
}
}The create method is the longest, and everything in it is HTTP work: building the Location URI and picking 201 Created. The decision to store the book is one call.
Why constructor injection
The controller declares private final BookService service and receives it through its constructor. Spring Boot injects it automatically when the class has a single constructor. This has practical benefits:
- The field is
final, so it cannot be left unset or replaced. - A unit test can build the controller with
new BookController(fakeService)and no Spring context. - A missing bean fails at startup, not on the first request.
Avoid field injection with @Autowired on a private field. It hides dependencies and makes the class impossible to construct by hand in a test.
What belongs where
The line between layers is easy to blur. This table gives a working rule for common tasks.
| Task | Layer | Reason |
|---|---|---|
| Parse JSON, bind path and query values | Controller | Framework binding is HTTP-specific |
| Trigger `@Valid` on the body | Controller | Validation of input shape happens at the boundary |
| Choose `201`, `204`, `Location` header | Controller | Status and headers are part of HTTP |
| Check uniqueness, ownership, state rules | Service | These are business rules |
| Open a transaction | Service | A transaction covers a unit of business work |
| Throw `BookNotFoundException` | Service | The service reports the domain failure |
| Map exception to `404` | Exception handler | One place decides how failures look on the wire |
| Query the database | Repository | Storage details stay out of the service |
A useful test: if you could call the method from a command-line tool without changing it, it belongs in the service.
Common mistakes
Passing HTTP types into the service
A signature like create(HttpServletRequest request) or get(ResponseEntity<?> entity) ties the service to the web layer. Pass plain values or DTOs instead.
Returning `ResponseEntity` from the service
The service should return the data or throw. If it returns ResponseEntity, it has taken over a decision the controller owns, and you cannot reuse it outside HTTP.
Returning `null` or `Optional` and checking in the controller
This works, but it spreads "not found" handling across every controller method. Throwing a domain exception from the service and handling it once in @RestControllerAdvice keeps controllers free of branches.
Exposing persistence entities directly
If you later add a JPA entity, do not return it from the controller. Map it to a response DTO. In the service, a small mapping method is enough. Returning entities leaks column names and lazy-loading problems into your public API, and any change to the table changes the contract.
A service that only forwards calls
If every service method just calls a repository method, the layer adds no value yet. That is acceptable when the logic really is trivial. Keep the layer anyway if the application will grow, because the service is where rules will land.
Calling one controller from another
When two controllers need the same behavior, extract it into a service and have both call it. A controller calling a controller carries HTTP concerns along with it.
Transactions belong in the service
When the service coordinates several repository calls, wrap them in a transaction so they succeed or fail together. Put @Transactional on the service method, not on the controller.
import org.springframework.transaction.annotation.Transactional;
@Service
public class BookService {
private final BookRepository repository;
public BookService(BookRepository repository) {
this.repository = repository;
}
@Transactional(readOnly = true)
public BookResponse get(long id) {
return repository.findById(id)
.map(book -> new BookResponse(book.getId(), book.getTitle(), book.getAuthor()))
.orElseThrow(() -> new BookNotFoundException(id));
}
}This sketch assumes a Spring Data JPA BookRepository and a Book entity, which this chapter does not define. It shows the shape: the service owns the transaction, maps the entity to a DTO, and throws the domain exception.
Testing the split
The split gives you two cheap kinds of test.
A service test needs no Spring at all:
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
class BookServiceTest {
private final BookService service = new BookService();
@Test
void createsAndFindsBook() {
BookResponse created = service.create(new CreateBookRequest("Dune", "Frank Herbert"));
assertEquals("Dune", service.get(created.id()).title());
}
@Test
void missingBookThrows() {
assertThrows(BookNotFoundException.class, () -> service.get(99L));
}
}This test uses the in-memory version of the service from earlier in the chapter. It runs in milliseconds and covers the business behavior.
A controller test, shown in the testing chapter, uses @WebMvcTest and a mocked BookService. It checks only the HTTP behavior: status codes, JSON shape, and headers. Because the service is mocked, those tests do not repeat the business rules.
Edge cases to keep in mind
- Validation location. Use
@Validin the controller for input shape (blank, too long). Check rules that need data, such as "this ISBN already exists", in the service. Both can fail, and both should end up as clear error responses. - DTO reuse. Request DTOs are fine as service arguments in a small application. In a larger one, consider a separate command object so the service does not depend on the web contract.
- Circular dependencies. If two services need each other, constructor injection fails at startup. Treat it as a sign that shared logic needs its own class.
- Several implementations. If you define an interface with more than one implementation, Spring cannot choose between them without
@Primaryor@Qualifier. For a single implementation, a plain class is enough, and you can introduce an interface later.
Exercise
A teammate's controller method calls a repository directly, checks whether the result is empty, and returns ResponseEntity.notFound().build(). List the changes that move it to a thin controller backed by a service, and name where the 404 is produced afterward.
Show answer
Create a @Service that takes the repository through its constructor. Move the lookup into a service method that returns the DTO or throws BookNotFoundException when nothing is found. Change the controller to inject the service and return service.get(id). The 404 is now produced by the @ExceptionHandler for BookNotFoundException in the @RestControllerAdvice class, which returns a ProblemDetail with status 404.
Exercise
Why does @Transactional on a method have no effect when another method of the same service calls it with this.method()?
Show answer
Spring applies @Transactional through a proxy around the bean. A call made from inside the class goes straight to the target object and skips the proxy, so no transaction is started. Move the method to another bean, or call it through the injected proxy.