This is the last blog's webflux demo that called Router configuration and bean
package org.spring.springboot.router;
import org.spring.springboot.handler.CityHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.server.RequestPredicates;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;
@Configuration
public class CityRouter {
@Bean
public RouterFunction<ServerResponse> routeCity(CityHandler cityHandler) {
return RouterFunctions
.route(RequestPredicates.GET("/hello")
.and(RequestPredicates.accept(MediaType.TEXT_PLAIN)),
cityHandler::helloCity);
}
}
It's tell me to visit the route of /hello to invoke that method called cityHandler::helloCity
Let's checkout the helloCity's code as follows:
package org.spring.springboot.handler;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;
@Component
public class CityHandler {
public Mono<ServerResponse> helloCity(ServerRequest request) {
return ServerResponse.ok().contentType(MediaType.TEXT_PLAIN)
.body(BodyInserters.fromObject("Hello, City!"));
}
}
The response entity is ServerResponse and bind ok() and contentType and the body is
BodyInserters.fromObject(...)
And download the source code of that fromObject method(function),shown below
/**
* Inserter to write the given object.
* <p>Alternatively, consider using the {@code syncBody(Object)} shortcuts on
* {@link org.springframework.web.reactive.function.client.WebClient WebClient} and
* {@link org.springframework.web.reactive.function.server.ServerResponse ServerResponse}.
* @param body the body to write to the response
* @param <T> the type of the body
* @return the inserter to write a single object
*/
public static <T> BodyInserter<T, ReactiveHttpOutputMessage> fromObject(T body) {
return (message, context) ->
writeWithMessageWriters(message, context, Mono.just(body), ResolvableType.forInstance(body));
}
The return type that called
Translation annotation
inserter to write the given object.
You can using the syncBody(Object) too
the body to write to the response
the
the returned is that inserter to write a single object
I can see the lambda function and the method writeWithMessageWriters(message,context,Mono.just(body),...
the Mono is just 0 or 1 object to insert
The resource link
https://www.bysocket.com/technique/2328.html