Sub topic 7
Annotated controllers that return Mono and Flux
This chapter assumes you know Spring Boot basics (beans, dependency injection, @RestController), you can read Java lambdas and generics, and you know what Mono and Flux represent. If map, flatMap, and switchIfEmpty are new, review the operators chapter first.
The programming model you already know
WebFlux keeps the annotation model from Spring MVC. You still use @RestController, @RequestMapping, @GetMapping, and @PathVariable. The change is the return type. Instead of returning a Book or a List<Book>, a handler returns a Mono<Book> or a Flux<Book>.
The handler does not produce the data when it runs. It returns a pipeline description. The framework subscribes to that pipeline, writes the result to the response, and frees the thread in the meantime.
| Result shape | MVC return type | WebFlux return type |
|---|---|---|
| Zero or one item | `Book` or `Optional<Book>` | `Mono<Book>` |
| Many items | `List<Book>` | `Flux<Book>` |
| No body | `void` | `Mono<Void>` |
A complete controller
@RestController
@RequestMapping("/books")
public class BookController {
private final BookRepository repository;
public BookController(BookRepository repository) {
this.repository = repository;
}
@GetMapping
public Flux<Book> list() {
return repository.findAll();
}
@GetMapping("/{id}")
public Mono<Book> get(@PathVariable String id) {
return repository.findById(id)
.switchIfEmpty(Mono.error(
new ResponseStatusException(HttpStatus.NOT_FOUND)));
}
}list() returns a Flux<Book>. By default, WebFlux collects the elements and writes a JSON array. get() returns a Mono<Book>. If the repository finds nothing, the Mono completes empty, and WebFlux would answer with a 200 and an empty body. switchIfEmpty replaces that empty completion with an error. ResponseStatusException then becomes a 404 response.
What the framework does for you
- Subscription. You never call
subscribein a controller. WebFlux subscribes when it is ready to write the response. - Serialization. A
Mono<T>is written as one JSON value. AFlux<T>is written as a JSON array, unless you choose a streaming media type. - Request bodies. You can also accept
Mono<Book>orFlux<Book>as a@RequestBodyparameter. Then the body is decoded without blocking.
Common errors
- Calling
block()in a handler. This defeats the model and can fail at runtime on an event-loop thread. Return the pipeline instead. - Forgetting that nothing runs without a subscriber. If you build a pipeline for a side effect, such as a save, and do not return it, it never executes.
- Treating an empty
Monoas an error. An empty result is a valid completion. Decide explicitly withswitchIfEmptywhether it means 404. - Mixing in blocking libraries. A JDBC call inside a handler stalls the event loop. A later chapter covers how to isolate such calls.
Exercise
A handler returns repository.findById(id) directly, and a client requests an id that does not exist. What status does the client receive, and how do you change it to 404?
Show answer
The client receives 200 with an empty body, because an empty Mono is a normal completion. Add .switchIfEmpty(Mono.error(new ResponseStatusException(HttpStatus.NOT_FOUND))) to the pipeline.