A functional web programming model defines reactive APIs with functions and composition instead of annotation-driven controllers. It treats request mapping more like using a library: predicates identify requests, routers connect them to handlers, and request and response objects carry HTTP data. section 12.2
A functional WebFlux endpoint is built from four primary types:
- RequestPredicate declares which requests a handler accepts. section 12.2
- RouterFunction declares how matching requests are routed to handler code. section 12.2
- ServerRequest represents the incoming HTTP request, including headers and body information. section 12.2
- ServerResponse represents the outgoing HTTP response, including headers and body information. section 12.2
A minimal functional route
A configuration class exposes a RouterFunction bean. The route matches GET requests for /hello and responds with a reactive Mono containing “Hello World!”. Additional routes can be composed with andRoute, keeping request predicates and handler functions together. 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))
;
}
}
Use the complete listing to see the configuration class, RouterFunction bean, GET predicate, handler lambda, and reactive response assembled in one endpoint. section 12.2
