In Spring WebFlux, a RouterFunction maps incoming requests to HandlerFunction instances, replacing the annotation-based mapping of @RequestMapping with plain, composable Java code. It is the core of the functional programming model: the router decides which handler runs, the handler returns a Mono<ServerResponse>, and WebFlux writes the response without blocking a thread.
Annotated controllers and functional routes run on the same reactive infrastructure, so you can choose per feature.
WebFlux supports two programming models:
@RestController, @GetMapping) that look like Spring MVC.RouterFunction and HandlerFunction.In the functional model, a DispatcherHandler finds your RouterFunction bean, asks it whether the request matches, and invokes the resulting handler. Spring Boot picks up any RouterFunction bean automatically, and you can have several.
Start with a handler class that depends on a reactive repository:
Then declare the route:
A request such as GET /hello?name=Ada returns:
A route is only chosen when its RequestPredicate matches. The RequestPredicates class provides the common ones:
| Predicate | Matches on |
|---|---|
GET(path), POST(path), PUT(path), DELETE(path) | HTTP method and path pattern |
path(pattern) | Path only |
accept(mediaType) | The Accept header |
contentType(mediaType) | The Content-Type header |
headers(...), queryParam(...) | Headers and query parameters |
Combine them with and, or and negate. You can also write your own RequestPredicate lambda, for example to route by tenant header, which is awkward to express with annotations.
The router itself is cheap. What matters is that your handlers return reactive types and never block the event loop. Avoid Thread.sleep, blocking JDBC calls and Mono.block() inside a handler. If you must call blocking code, wrap it and move it off the event loop:
For new applications that mostly need to scale blocking I/O, virtual threads with Spring MVC are an alternative worth comparing with WebFlux.
Because the route is a plain object, the test needs no application context.
RouterFunction selects a handler for a request. HandlerFunction contains the logic that handles it and returns the response.
Yes. Spring Security's WebFlux support works at the web filter level, so it protects functional routes by path. Configure it with a SecurityWebFilterChain.
Use annotated controllers if you want automatic validation and binding. Use RouterFunction if you value explicit routing and programmatic composition. Mixing them is supported.
No. WebFlux runs on Netty, Tomcat, Jetty or Undertow, and RouterFunction works the same on all of them.
RouterFunction is WebFlux's functional router. It matches requests with predicates and hands them to HandlerFunction methods that return Mono<ServerResponse>. Declare it as a bean, keep handlers non-blocking, compose routes with and, andRoute and nesting, and test it directly with WebTestClient.bindToRouterFunction.