original link: https://dzone.com/articles/spring-webflux-kotlin-dsl-snippetsBiju kunjummen translator: Jackie Tang
If you have not yet played with spring Webflux, you can develop a functional API using a Kotlin-based DSL.
Spring Webflux recently introduced a feature to define the functional API, which uses a very intuitive Kotlin-based DSL.
This article will simply show a set of contrasting ways to define the API, one based on Java's Fluent API and one based on the Kotlin DSL.
In Java, a functional programming style is used to define a set of CRUD Spring Webflux APIs, which are typically:
RouterFunction<?> apis() { return nest(path("/hotels"), nest(accept(MediaType.APPLICATION_JSON), route( GET("/"), messageHandler::getMessages) .andRoute(POST("/"), messageHandler::addMessage) .andRoute(GET("/{id}"), messageHandler::getMessage) .andRoute(PUT("/{id}"), messageHandler::updateMessage) .andRoute(DELETE("/{id}"), messageHandler::deleteMessage) ));}
The details of these APIs are very clear and are defined in a fluent way with only a few keywords--route, nest, and HTTP behavior.
These APIs can also be implemented using Kotlin-based DSLs (and some cleverly using Kotlin extension functions) in the following ways:
@Beanfun apis() = router { (accept(APPLICATION_JSON) and "/messages").nest { GET("/", messageHandler::getMessages) POST("/", messageHandler::addMessage) GET("/{id}", messageHandler::getMessage) PUT("/{id}", messageHandler::updateMessage) DELETE("/{id}", messageHandler::deleteMessage) }}
I think this is better than a Java-based DSL in terms of readability. If the API is more complex, as shown in the wonderful example Sébastien Deleuze demonstrates, there are multiple levels of nesting, and the benefits of Kotlin DSL are obvious.
In the next article, I'll look into how this support is implemented.
This example can be found in my GitHub repo here.
This article was created by spring4all.com translation teams, using knowledge sharing-attribution-non-commercial use-sharing 4.0 international license agreements in the same way.
http://www.spring4all.com/article/1131
Spring Webflux:kotlin DSL [fragment]