如何使用新方式編寫Spring MVC接口
1. 前言
通常我們編寫 Spring MVC 接口的范式是這樣的:
@RestController@RequestMapping('/v1/userinfo')public class UserInfoController { @GetMapping('/foo') public String foo() { return 'felord.cn'; }}
這種我都寫吐了,今天換個口味,使用 Spring 5 新引入的函數(shù)式端點(Functional Endpoints)來耍耍。這種方式同樣支持 Spring Webflux。
請注意可使用該特性的 Spring 版本不低于 Spring 5.2
2. 依賴
為了演示,這里極簡化只引入 Spring MVC 的 starter :
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency>
3. RouterFunction
在函數(shù)式端點的寫法中,傳統(tǒng)的請求映射(@RequestMapping)被路由函數(shù)(RouterFunction)所代替。上面的寫法等同于:
@Bean public RouterFunction<ServerResponse> fooFunction() { return RouterFunctions.route().GET('/v1/userinfo/foo', request -> ServerResponse.ok() .body('felord.cn')).build(); }
在該示例中,我使用了 RouterFunctions.route() 創(chuàng)建了一個RouterFunction,然后RouterFunction 提供了從請求到響應(yīng)的細節(jié)操作。
4. ServerRequest/ServerResponse
ServerRequest 是對服務(wù)器端的 HTTP 請求的抽象,你可以通過該抽象獲取請求的細節(jié)。對應(yīng)的,ServerResponse 是對服務(wù)器端響應(yīng)的抽象,你也可以通過該抽象構(gòu)建響應(yīng)的細節(jié)。這兩個概念由下面的 HandlerFunction 接口進行 請求 → 響應(yīng) 處理。
5. HandlerFunction
HandlerFunction 是一個函數(shù)式接口,它提供了從請求( ServerRequest)到響應(yīng)(ServerResponse)的函數(shù)映射抽象。通常你的業(yè)務(wù)邏輯由該接口進行實現(xiàn)。從 ServerRequest 中獲取請求的細節(jié),然后根據(jù)業(yè)務(wù)構(gòu)建一個 ServerResponse 響應(yīng)。
HandlerFunction<ServerResponse> handlerFunction = request -> ServerResponse.ok().body('felord.cn');
6. RequestPredicate
RequestPredicate 可以讓你根據(jù)請求的一些細節(jié),比如 請求方法、請求頭、請求參數(shù)等等進行斷言以決定是否路由。
這里舉一個例子,假如我們希望請求接口/v1/userinfo/predicate時根據(jù)不同的參數(shù)處理不同的業(yè)務(wù),當攜帶參數(shù) 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(); }
然后我們測試一下:
當攜帶參數(shù) plan時:
GET http://localhost:8080/v1/userinfo/predicate?plan=
HTTP/1.1 200Content-Type: text/plain;charset=UTF-8Content-Length: 9Date: Thu, 14 May 2020 07:57:35 GMTKeep-Alive: timeout=60Connection: keep-alive
felord.cn
不攜帶參數(shù)plan時:
GET http://localhost:8080/v1/userinfo/predicateHTTP/1.1 404Vary: OriginVary: Access-Control-Request-MethodVary: Access-Control-Request-HeadersContent-Type: application/jsonTransfer-Encoding: chunkedDate: Thu, 14 May 2020 08:00:15 GMTKeep-Alive: timeout=60Connection: keep-alive{ 'timestamp': '2020-05-14T08:00:15.659+0000', 'status': 404, 'error': 'Not Found', 'message': 'No message available', 'path': '/v1/userinfo/predicate'}
7. 小結(jié)
函數(shù)式端點是 Spring 5 提供的一個新的接口范式風格,對于 Spring MVC 來說 Spring 5.2 才進行了支持。也是順應(yīng)函數(shù)式編程的一個未來趨勢。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
