A RouterFunction maps matching HTTP requests to handler functions in Spring WebFlux’s functional programming model. It offers a library-like alternative to annotation-based request mappings. section 12.2
A functional reactive API combines four types:
- RequestPredicate identifies requests to handle. section 12.2
- RouterFunction connects matching predicates to handler code. section 12.2
- ServerRequest provides HTTP request data, including headers and body. section 12.2
- ServerResponse builds the returned HTTP response. section 12.2
A GET route
Declare a RouterFunction bean and use route(GET("/hello"), handler) to match GET requests. The lambda receives a ServerRequest and returns ServerResponse.ok().body(...), producing a reactive response such as “Hello World!”. Additional routes can be chained with andRoute. section 12.2
package hello;
import static org.springframework.web
.reactive.function.server.RequestPredicates.GET;
import static org.springframework.web
.reactive.function.server.RouterFunctions.route;
import static org.springframework.web
.reactive.function.server.ServerResponse.ok;
import static reactor.core.publisher.Mono.just;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.server.RouterFunction;
@Configuration
public class RouterFunctionConfig {
@Bean
public RouterFunction<?> helloRouterFunction() {
return route(GET("/hello"),
request -> ok().body(just("Hello World!"), String.class))
;
}
}
Inspect a complete configuration class that defines a RouterFunction bean for a reactive Hello World endpoint. section 12.2
