# new
# Spring MVC 还能这么写
通常我们编写 Spring MVC 接口的范式是这样的:
@RestController
@RequestMapping("/v1/userinfo")
public class UserInfoController {
@GetMapping("/foo")
public String foo() {
return "felord.cn";
}
}
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
使用 Spring 5 新引入的
函数式端点(Functional Endpoints)来耍耍。 这种方式同样支持 Spring Webflux。
在函数式端点的写法中,传统的请求映射(@RequestMapping)被路由函数(RouterFunction)所代替。上面的写法等同于:
@Bean
public RouterFunction<ServerResponse> fooFunction() {
return RouterFunctions.route()
.GET("/v1/userinfo/foo", request -> ServerResponse.ok()
.body("felord.cn"))
.build();
}
1
2
3
4
5
6
7
2
3
4
5
6
7
# ServerRequest/ServerResponse
ServerRequest 是对服务器端的HTTP请求的抽象,你可以通过该抽象获取请求的细节。对应的,ServerResponse 是对服务器端响应的抽象,你也可以通过该抽象构建响应的细节。这两个概念由下面的 HandlerFunction 接口进行 请求→ 响应 处理。
# 5. HandlerFunction
HandlerFunction 是一个函数式接口,它提供了从请求( ServerRequest)到响应(ServerResponse)的函数映射抽象。通常你的业务逻辑由该接口进行实现。从 ServerRequest 中获取请求的细节,然后根据业务构建一个 ServerResponse 响应。
HandlerFunction<ServerResponse> handlerFunction = request -> ServerResponse.ok().body("felord.cn");
1
# 6. RequestPredicate
RequestPredicate 可以让你根据请求的一些细节,比如 请求方法、请求头、请求参数等等进行断言以决定是否路由。
假如我们希望请求接口/v1/userinfo/predicate时根据不同的参数处理不同的业务,当携带参数 plan时才能进行处理。我们可以这么写:
@Bean
public RouterFunction<ServerResponse> predicateFunction() {
return RouterFunctions.route()
.GET("/v1/userinfo/predicate",
request -> request.param("plan").isPresent(),
request -> ServerResponse.ok().body("felord.cn"))
.build();
}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8