【Kotlin】SpringBootでGetのコントローラーを動かすまで【SpringBoot】

最近黒べこ本(会社のお金で)買いました。サーバーサイドでもKotlinはいいぞ。
今回はKotlinのSpringBootでハロワします。
記事執筆時点でのプロジェクトリポジトリは以下。
github.com

やること

  1. SpringInitializrでプロジェクトの概形を作る
  2. Controllerを追加する
SpringInitializrでプロジェクトの概形を作る

https://start.spring.io/
使い方はネット上に解説記事が有るので省略します。
自分はGradle Project/Kotlin、Spring Boot 2.1.1で初期化しました。
f:id:wrongwrongwrongwrong163377:20181202144343p:plain
そのままやるとパッケージ名が大文字になってしまうので、その点は修正を行いました。

Controllerを追加する

以下のような形でMyControllerという名前でコントローラーを追加しました。
f:id:wrongwrongwrongwrong163377:20181202144505p:plain

import org.springframework.ui.Model
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController

@RestController
@RequestMapping("my")
class MyController{
    @GetMapping
    fun myGetTest(model: Model): String{
        return "hello from spring boot"
    }
}

このままだとimplementsが足りなかったり警告が出たりするので、build.gradleに以下の2つを追加します。

implementation(group: 'org.springframework.boot', name: 'spring-boot-starter-web')
implementation("com.fasterxml.jackson.module:jackson-module-kotlin")

追加後全文。

buildscript {
	ext {
		kotlinVersion = '1.2.71'
		springBootVersion = '2.1.1.RELEASE'
	}
	repositories {
		mavenCentral()
	}
	dependencies {
		classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
		classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:${kotlinVersion}")
		classpath("org.jetbrains.kotlin:kotlin-allopen:${kotlinVersion}")
	}
}

apply plugin: 'kotlin'
apply plugin: 'kotlin-spring'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

group = 'com.wrongwrong'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
compileKotlin {
	kotlinOptions {
		freeCompilerArgs = ["-Xjsr305=strict"]
		jvmTarget = "1.8"
	}
}
compileTestKotlin {
	kotlinOptions {
		freeCompilerArgs = ["-Xjsr305=strict"]
		jvmTarget = "1.8"
	}
}

repositories {
	mavenCentral()
}

dependencies {
	implementation('org.springframework.boot:spring-boot-starter')
	implementation(group: 'org.springframework.boot', name: 'spring-boot-starter-web')

	implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
	implementation("org.jetbrains.kotlin:kotlin-reflect")

	implementation("com.fasterxml.jackson.module:jackson-module-kotlin")

	testImplementation('org.springframework.boot:spring-boot-starter-test')
}

アクセス結果

動かした上でhttp://localhost:8080/myへアクセスすると、以下が表示されます。
f:id:wrongwrongwrongwrong163377:20181202145028p:plain

続き

バリデーションまでやってます。
wrongwrong163377.hatenablog.com