An Easy Application With Spring Boot and Kotlin

An Easy Application With Spring Boot and Kotlin

Diego Brener da Silva's photo
Diego Brener da Silva
·Aug 2, 2022·

2 min read

Starting

Today I will show you guys how easy is to start and running a Spring Boot application.

So let's go.

First we will access the Spring initialize to start our first project.

Follow the steps:

  • Project: Choose gradle project
  • Language: Kotlin
  • Spring Boot: 2.7.2
  • Group: com.myexample
  • Packaging: jar
  • Java: Java version executing in your machine(Here is Java 11)
  • Dependencies: Spring Reactive Web.

Screen Shot 2022-08-01 at 23.05.13.png

After the previous step just click on Generate

Importing and writing some code

You can import the project to you favorite IDE. Here I am using Intellij IDEA.

With your project imported you can see the following structure

Screen Shot 2022-08-01 at 23.08.11.png

now we will create two classes inside the package com.myexample.demo

MyFirstRoute

 package com.myexample.demo

import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.http.MediaType
import org.springframework.web.reactive.function.server.coRouter

@Configuration
class MyFirstRoute {

    @Bean
    fun route(handler: MyFirstHandler) = coRouter {
        accept(MediaType.APPLICATION_JSON).nest {
            "v1".nest {
                GET("/hello", handler::handle)
            }
        }
    }
}

MyFirstHandler

package com.myexample.demo

import org.springframework.stereotype.Component
import org.springframework.web.reactive.function.server.ServerRequest
import org.springframework.web.reactive.function.server.ServerResponse
import org.springframework.web.reactive.function.server.bodyValueAndAwait

@Component
class MyFirstHandler {

    suspend fun handle(request: ServerRequest): ServerResponse{
        return ServerResponse.ok().bodyValueAndAwait("That's so easy!! ")
    }
}

Now our project structure it looks like that

Screen Shot 2022-08-01 at 23.11.30.png

To test our project you just need to run the main class DemoApplication. With the app running go to your browser and type the address http://localhost:8080/v1/hello.

That's it.

Did you find this article valuable?

Support Diego Brener da Silva by becoming a sponsor. Any amount is appreciated!

Learn more about Hashnode Sponsors
 
Share this