Sub topic 7
Annotated controllers that return Mono and Flux
This chapter assumes you know Spring MVC annotations such as @RestController and @GetMapping. It also assumes you have read the earlier chapters on Mono, Flux, operators, and the WebFlux event loop. If you can write Mono.just(x).map(...), you are ready.
Annotated controllers are the most familiar way to build WebFlux endpoints. The annotations are the same ones you use in Spring MVC. What changes is the method signature: instead of returning a value, a handler method returns a publisher that will produce the value later.
The model: you return a description, the framework subscribes
A publisher does nothing until someone subscribes. In a WebFlux controller, you never call subscribe(). You build a pipeline and return it. WebFlux subscribes when it is ready to write the response, then writes each signal to the HTTP connection.
The handler method runs quickly on an event-loop thread and returns. The data flows later, as results arrive.
A basic controller
This controller uses a reactive repository (covered in a later chapter). It assumes BookRepository extends ReactiveCrudRepository<Book, String>.
@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 them as one JSON array, application/json. get() returns a Mono<Book> and writes one JSON object.
Return types at a glance
| Return type | What WebFlux does |
|---|---|
| `Mono<T>` | Writes one body when the `Mono` emits. If it completes empty, the response has an empty body and status 200. |
| `Flux<T>` | Writes a JSON array for `application/json`. With `text/event-stream` or `application/x-ndjson`, it writes each element as it arrives. |
| `Mono<ResponseEntity<T>>` | Lets you choose the status and headers at runtime, after the data is known. |
| `Mono<Void>` | Writes no body. The response is sent when the `Mono` completes. |
| `T` (plain value) | Works, but the method has already finished, so nothing is deferred. Fine for cheap, non-blocking values. |
The empty case catches many people out. An empty Mono<Book> is not an error. It produces a 200 with no body. Use switchIfEmpty or defaultIfEmpty when you want a 404 instead, as get() does above.
Choosing the status code
There are three common ways to control the status.
For a fixed success status, use @ResponseStatus:
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public Mono<Book> create(@RequestBody Mono<Book> body) {
return body.flatMap(repository::save);
}For a status that depends on the data, return Mono<ResponseEntity<T>>:
@GetMapping("/{id}/entity")
public Mono<ResponseEntity<Book>> getEntity(@PathVariable String id) {
return repository.findById(id)
.map(ResponseEntity::ok)
.defaultIfEmpty(ResponseEntity.notFound().build());
}For failures, emit an error signal. ResponseStatusException is turned into a response with that status. Errors are covered in depth in a later chapter.
Reading request data
Request parameters, path variables, headers, and cookies are plain values, exactly as in Spring MVC. They are available immediately, so you can declare them as String, int, and so on:
@GetMapping("/search")
public Flux<Book> search(@RequestParam String author) {
return repository.findAll()
.filter(book -> author.equalsIgnoreCase(book.author()));
}This filters in memory for simplicity. In a real application you would add a derived query method to the repository so the database does the filtering.
The request body is different, because it may not have arrived yet. You have two options:
@RequestBody Book bookmakes WebFlux wait until the body is fully read and decoded, then call your method. Your method code never sees the waiting.@RequestBody Mono<Book> bookcalls your method right away and gives you a handle to the future body. For a streamed upload, useFlux<Book>to receive elements as they are decoded.
Both work. The Mono form lets you build the whole pipeline in one expression, with no intermediate variables.
@PutMapping("/{id}")
public Mono<Book> update(@PathVariable String id, @RequestBody Mono<Book> body) {
return body
.flatMap(incoming -> repository.findById(id)
.switchIfEmpty(Mono.error(
new ResponseStatusException(HttpStatus.NOT_FOUND)))
.map(existing -> new Book(existing.id(), incoming.title(), incoming.author()))
)
.flatMap(repository::save);
}This code assumes Book is a record such as record Book(String id, String title, String author) {}. A Spring Data entity would normally also carry an @Id annotation on the id field.
A delete endpoint and `Mono<Void>`
Repository delete methods return Mono<Void>. A Mono<Void> never emits a value, so map and flatMap after it never run. Use then to continue once it completes:
@DeleteMapping("/{id}")
public Mono<ResponseEntity<Void>> delete(@PathVariable String id) {
return repository.findById(id)
.flatMap(book -> repository.delete(book)
.then(Mono.just(ResponseEntity.noContent().<Void>build())))
.defaultIfEmpty(ResponseEntity.notFound().build());
}If the book is missing, findById is empty, the flatMap is skipped, and defaultIfEmpty supplies the 404.
Common errors
Calling `block()` or `subscribe()` in a handler
Calling block() on the event loop throws an IllegalStateException in Reactor, because blocking is not allowed on those threads. Calling subscribe() yourself detaches the work from the response. The response completes before your pipeline finishes, and any errors disappear. Return the publisher instead.
Building a pipeline and not returning it
@PostMapping("/bad")
public Mono<Void> bad(@RequestBody Book book) {
repository.save(book); // returns a Mono, but nobody subscribes
return Mono.empty();
}The save call only creates a description of the work. It never runs, so nothing is saved. Chain it into the returned pipeline:
@PostMapping("/good")
public Mono<Void> good(@RequestBody Book book) {
return repository.save(book).then();
}Blocking inside the pipeline
A JDBC call, a Thread.sleep, or a blocking HTTP client inside map stalls an event-loop thread. A few slow requests can then stall every request on that thread. The threading chapter shows how to isolate such calls with Schedulers.
Returning `null`
A reactive method must never return null, and Mono.just(null) throws a NullPointerException. Use Mono.empty() or Mono.justOrEmpty(value) for an absent value.
Assuming order across `flatMap`
flatMap runs inner publishers concurrently and may emit results out of order. If response order matters, use concatMap.
Content negotiation and streaming
The produces attribute changes how a Flux is written. With the default JSON type, the framework waits for the Flux to complete and writes one array. With text/event-stream, each element is sent as it arrives:
@GetMapping(path = "/ticks", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<Long> ticks() {
return Flux.interval(Duration.ofSeconds(1));
}The streaming chapter covers this in more detail. For now, note that the return type stays the same and only the media type changes.
Annotated controllers compared with MVC
Choose annotated controllers when your team knows Spring MVC and you want a gradual move to reactive. Choose functional endpoints, covered in the next chapter, when you prefer to declare routes as code.
Exercise
A handler is declared as public Mono<Book> find(@PathVariable String id) { return repository.findById(id); }. A client requests an id that does not exist and gets a 200 response with an empty body. What change makes the endpoint return 404, and why does the original return 200?
Show answer
The original returns 200 because an empty Mono is a normal completion with no value, and WebFlux writes an empty body with status 200. Add .switchIfEmpty(Mono.error(new ResponseStatusException(HttpStatus.NOT_FOUND))) to the pipeline. When findById completes without a value, the fallback publisher emits an error, and ResponseStatusException becomes a 404 response. You could also return Mono<ResponseEntity<Book>> and use map(ResponseEntity::ok).defaultIfEmpty(ResponseEntity.notFound().build()).
Exercise
Why does the following method save nothing, and how do you fix it?
@PostMapping public Mono<Void> add(@RequestBody Book b) { repository.save(b); return Mono.empty(); }
Show answer
repository.save(b) returns a Mono that only describes the save. Nothing subscribes to it, because the method returns a different publisher, Mono.empty(). Return the save pipeline instead: return repository.save(b).then();. WebFlux then subscribes to the returned Mono<Void>, the save runs, and the response completes when it finishes.