0 day streak
java / expert
Snippet

Declarative Request Routing with Custom WebFlux RequestPredicates

Spring WebFlux allows functional HTTP endpoint routing using `RouterFunction` and `RequestPredicates`. By combining functional predicates into custom request evaluation logic, control flow branching can inspect headers dynamically without relying on annotation-based controller mappings.

snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
public class HeaderRoutingConfig {
public RouterFunction<ServerResponse> routeByApiVersion(OrderHandler handler) {
return RouterFunctions.route(
RequestPredicates.all()
.and(req -> req.headers().header("X-Api-Version").contains("v2")),
handler::getOrdersV2
).andRoute(
RequestPredicates.all(),
handler::getOrdersV1
);
}
}
spring
Breakdown
1
public RouterFunction<ServerResponse> routeByApiVersion(OrderHandler handler)
Declares a functional web routing component mapping incoming server requests to handler responses.
2
RequestPredicates.all().and(req -> req.headers().header("X-Api-Version").contains("v2"))
Evaluates custom Predicate functional control flow to inspect request header arrays for version matching.
3
handler::getOrdersV2
Binds matching requests to the V2 handler method via method reference.
4
.andRoute(RequestPredicates.all(), handler::getOrdersV1)
Configures a fallback control flow branch routing non-matching requests to the legacy V1 handler.