Over a million developers have joined DZone.

Spring Webflux: Kotlin DSL [Snippets]

DZone's Guide to

Spring Webflux: Kotlin DSL [Snippets]

If you haven't kept up with Spring Webflux, you can now define functional application endpoints with a Kotlin-based DSL.

· Java Zone ·
Free Resource

Download Microservices for Java Developers: A hands-on introduction to frameworks and containers. Brought to you in partnership with Red Hat.

Spring Webflux recently introduced a feature to define functional application endpoints using a very intuitive Kotlin-based DSL.

This post will be to simply show a contrasting API defined using a Java-based fluent API and a Kotlin based DSL.

A functional way to define a CRUD-based Spring Webflux endpoint in Java would look like this:

RouterFunction<?> apis() {
    return nest(path("/hotels"), nest(accept(MediaType.APPLICATION_JSON),
                    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 the endpoint are very clear and are defined in a fluent manner with just a few keywords — route, nest, and the HTTP verbs.

These endpoints can be expressed using a Kotlin-based DSL (and some clever use of Kotlin extension functions) the following way:

fun 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 feel that this reads a little better than the Java-based DSL. If the API is more complicated, as demonstrated in the excellent samples by Sébastien Deleuze with multiple levels of nesting, the Kotlin-based DSL really starts to shine.

In the next post, I will delve into how this support has been implemented.

This sample is available in my GitHub repo here.

Download Building Reactive Microservices in Java: Asynchronous and Event-Based Application Design. Brought to you in partnership with Red Hat

java ,kotlin ,dsl ,spring webflux

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}