Sub topic 8
Functional endpoints with RouterFunction
This chapter assumes you know Spring Boot basics, how annotated WebFlux controllers return Mono and Flux, and Java lambdas. Functional endpoints are the second way to expose HTTP routes in WebFlux. They produce the same behavior as @RestController classes, but you declare routes as values in code instead of as annotations.
The two building blocks
A functional endpoint has two parts:
- A
HandlerFunctiontakes aServerRequestand returns aMono<ServerResponse>. It holds the logic. - A
RouterFunctionmaps a request predicate (method, path, headers) to a handler. It holds the routing.
Spring finds every RouterFunction bean and combines them into one routing table.
A complete example
The router is a bean. The handler is a normal component with one method per route.
@Configuration
public class BookRoutes {
@Bean
RouterFunction<ServerResponse> bookRoutes(BookHandler handler) {
return RouterFunctions.route()
.GET("/fbooks/{id}", handler::get)
.build();
}
}
@Component
class BookHandler {
private final BookRepository repository;
BookHandler(BookRepository repository) {
this.repository = repository;
}
Mono<ServerResponse> get(ServerRequest request) {
return repository.findById(request.pathVariable("id"))
.flatMap(book -> ServerResponse.ok().bodyValue(book))
.switchIfEmpty(ServerResponse.notFound().build());
}
}Read the handler step by step:
request.pathVariable("id")reads the value from the URL. There is no@PathVariable, because the handler receives the whole request object.findByIdreturns aMono<Book>.flatMapturns a found book into aMono<ServerResponse>.ServerResponse.ok().bodyValue(book)returns aMono, soflatMapis the right operator here, notmap.- If the repository emits nothing,
switchIfEmptysupplies a 404 response.
Compare this with the annotated version, which throws a ResponseStatusException for the empty case. In a handler you build the response yourself, so the status is part of the return value.
Grouping routes
The builder can group routes under a shared path with path, and it can attach several methods to one path. Handler methods stay small and each does one job.
@Bean
RouterFunction<ServerResponse> bookApi(BookHandler handler) {
return RouterFunctions.route()
.path("/fbooks", builder -> builder
.GET("/{id}", handler::get)
.GET(handler::list)
.POST(handler::create))
.build();
}This sketch assumes your BookHandler also has list and create methods with the same signature as get. Routes are checked in the order you declare them. The first match wins, so put specific paths before general ones.
Annotated or functional?
| Question | Annotated controller | Functional endpoint |
|---|---|---|
| Routing lives in | Annotations on methods | A `RouterFunction` bean |
| Request access | Method parameters | `ServerRequest` object |
| Response | Return a value or `Mono` | Build a `ServerResponse` |
| Cross-cutting rules | `@ControllerAdvice`, filters | `filter` on the router, `WebFilter` |
| Tooling familiarity | Most Spring teams know it | Less common, more explicit |
Both styles run on the same reactive stack, so there is no performance reason to choose one. Choose functional endpoints when you want routes built from data, composed in code, or easy to test without a Spring context. Choose annotations when your team already uses them and you want validation and argument binding with little code.
Exercise
In the handler above, why does the code use flatMap and not map to turn a Book into a response?
Show answer
ServerResponse.ok().bodyValue(book) returns a Mono<ServerResponse>, not a plain ServerResponse. map would produce a Mono<Mono<ServerResponse>>. flatMap flattens it into the Mono<ServerResponse> the handler must return.
Exercise
A route .GET("/{id}", ...) is declared before .GET("/search", ...) in the same router. What goes wrong, and how do you fix it?
Show answer
Routes are matched in declaration order, so a request to /search matches /{id} first and the search handler never runs. Declare /search before /{id}.