liveBook · Manning

Routerfunction

As explained in Spring in Action, Sixth Edition

A functional web API type that maps matching requests to handler functions.

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

How Spring in Action, Sixth Edition covers it

How deep it goes
Explains predicates, handlers, requests, responses, lambdas, and chained routes through a working example.
Examples
Uses a GET /hello route returning “Hello World!” and demonstrates adding a GET /bye route.
What it assumes
Assumes basic Java and HTTP familiarity while introducing the functional WebFlux request and response types.
What you can do after
Build it from scratch by declaring RouterFunction beans and routing predicates to reactive handler lambdas.
How it connects
Connects RequestPredicate, ServerRequest, ServerResponse, reactive programming, and annotation-based request mappings.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Spring in Action, Sixth Edition. The section links point to the parts of the book it draws on.