Java API vs Kotlin DSL

FILE : IntroSpring0.kt

Run main and enter url : http://localhost:8060/users/1

In file IntroSpring0.kt you can find an example on how to use clean Java API in Kotlin in order to configure Spring without any annotations.

Configure Routing

First let's discuss how to configure web routing. Single route contains of predicate and a handler function. First one answer a question if given request should be handled by specific handler and the second one decides what should be done.

Handler is a very simple functional interface :

@FunctionalInterface
public interface HandlerFunction<T extends ServerResponse> {

    /**
     * Handle the given request.
     * @param request the request to handle
     * @return the response
     */
    Mono<T> handle(ServerRequest request);

}

And usage of this interface is little problematic in Kotlin because compiler needs additional information on lambda type. So in Kotlin we need to provide this hint by writing HandlerFunction in fornt of a lambda

fun createJavaRouter(repo:MessageRepository) : RouterFunction<ServerResponse> {
    val healthCheck: HandlerFunction<ServerResponse> =  HandlerFunction{ _ -> ServerResponse.noContent().build()}

HandlerFunction returns Mono so it is dedicated to asynchronous operations. Mono is a part of project called Reactor which is also maintained by spring team.

In our example we have small simulation of blocking repository which doesn't really use any "reactive stuff" . You can see in "createJavaRouter" that it is the place where we can use many Spring builders which wraps our constructions - like Options in this example - into Reactor Types.

fun createJavaRouter(repo:MessageRepository) : RouterFunction<ServerResponse> {
...
        fun findMessage(id:Int): Mono<ServerResponse> =
                repo.find(id).fold(
                        ifEmpty = {ServerResponse.notFound().build()},
                        ifSome = {message3 -> ServerResponse.ok().syncBody(message3)}
                )

            fun messageHandler() = HandlerFunction {r ->
                val id=r.pathVariable("id").toInt()
                findMessage(id)
            }

Also notice how we just passed repository in order to use it in routers.

results matching ""

    No results matching ""