KotlinとSpring BootのアプリケーションでHello Worldを返すエンドポイントを実装する


Spring Initializrを使って生成する

  • Gradle
  • Kotlin
  • Spring Boot
  • Spring Boot Web

Spring Initializr、12月28日現在ですがまだクリスマス仕様ですね。

APIエンドポイントを作成する

@RestControllerアノテーションを利用してBeanを作成、APIリクエストした際のエンドポイントを用意します。

package com.example.helloworld

import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RestController

@RestController
class HelloWorldController {

    @GetMapping("/hello-world")
    fun helloWorld() = "Hello, World!"

}

Applicationを起動する

gradle bootRunでアプリケーションを起動、デフォルトポートは8080です。

$ helloworld gradle bootRun
> Task :bootRun
    .   ____          _            __ _ _
    /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
    \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
        '  |____| .__|_| |_|_| |_\__, | / / / /
    =========|_|==============|___/=/_/_/_/
    :: Spring Boot ::        (v2.2.2.RELEASE)
2019-12-28 11:00:58.215  INFO 48835 --- [           main] c.e.helloworld.HelloworldApplicationKt   : Starting HelloworldApplicationKt on noguchiasanoMBP with PID 48835 (/Users/noguchi_tsukasa/Downloads/helloworld/build/classes/kotlin/main started by noguchi_tsukasa in /Users/noguchi_tsukasa/Downloads/helloworld)
2019-12-28 11:00:58.218  INFO 48835 --- [           main] c.e.helloworld.HelloworldApplicationKt   : No active profile set, falling back to default profiles: default
2019-12-28 11:00:58.873  INFO 48835 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2019-12-28 11:00:58.882  INFO 48835 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2019-12-28 11:00:58.883  INFO 48835 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.29]
2019-12-28 11:00:58.946  INFO 48835 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2019-12-28 11:00:58.946  INFO 48835 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 686 ms
2019-12-28 11:00:59.086  INFO 48835 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2019-12-28 11:00:59.259  INFO 48835 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2019-12-28 11:00:59.264  INFO 48835 --- [           main] c.e.helloworld.HelloworldApplicationKt   : Started HelloworldApplicationKt in 1.339 seconds (JVM running for 1.694)

APIにcurlでアクセスする

$ curl localhost:8080/hello-world
Hello, World!

Hello, World!