Spring Bootでkotlinを使う

# はじめに
人伝えにKotlinが来ているということでSpring Bootで試してみました。
昨日書いた以下の記事のKotlin版です。

[Spring Bootでgroovyを使う](http://qiita.com/gosshys/items/137980f730c47fd34eb0)

# 手順
前回同様、[Spring BootをHerokuにデプロイするのが劇的に簡単になっている件](http://qiita.com/gosshys/items/6d409a245a108ad25202)で紹介した、SpringInitializrを使ったプロジェクトを流用します。

- build.gradleに以下を設定
  - buildscript.extに`kotlin_version`を追加する
  - buildscript.dependenciesにkotlin-gradle-pluginを追加する
  - pluginにkotlinを追加する
  - dependenciesにkotlin-stdlibを追加する
- kotlinのパッケージを作成
- kotlinのクラスを作成
- 起動確認

## build.gradleの内容

build.gradleファイル編集後は、更新を忘れずに...

```
buildscript {
	ext {
		springBootVersion = '1.4.2.RELEASE'
		kotlin_version = '1.0.5-2' // ココを追加　
	}
	repositories {
		mavenCentral()
	}
	dependencies {
		classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
		classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:${kotlin_version}"
	}
}

apply plugin: 'java'
apply plugin: 'kotlin' // ココを追加
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'

jar {
	baseName = 'demo'
	version = '0.0.1-SNAPSHOT'
}
sourceCompatibility = 1.8
targetCompatibility = 1.8

repositories {
	mavenCentral()
}


dependencies {
	compile("org.jetbrains.kotlin:kotlin-stdlib:${kotlin_version}")  // ココを追加
	compile('org.springframework.boot:spring-boot-starter-actuator')
	compile('org.springframework.boot:spring-boot-starter-web')
	testCompile('org.springframework.boot:spring-boot-starter-test')
}
```

## kotlinのパッケージを作成

### Projectペインのmainフォルダを右クリックして、「New」->「Directory」を選択
![image](https://qiita-image-store.s3.amazonaws.com/0/38174/f6745df7-829c-5d47-dcf2-d9aa9d1a8e5a.png)
### 「New Directory」ダイアログに`kotlin`と入力
![image](https://qiita-image-store.s3.amazonaws.com/0/38174/e153e2a3-a35e-9626-afed-811648efdac0.png)
### 作成したkotlinフォルダを右クリックして、「Mark Directory as」メニューから「Sources Root」を選択
![image](https://qiita-image-store.s3.amazonaws.com/0/38174/deb9ff0a-3346-a13b-5a62-f89d213ecb2c.png)
### kotlinフォルダを右クリックして、「New」->「package」
![image](https://qiita-image-store.s3.amazonaws.com/0/38174/3c9bbda7-afaf-50d1-41c4-e52a90098e81.png)
### 「New Package」ダイアログにcom.example.controllerを入力
![image](https://qiita-image-store.s3.amazonaws.com/0/38174/0497b3ee-db92-b40d-1033-1889f4e4b812.png)

## Kotlinのクラスを作成

### 作成したパッケージを右クリックして、「New」->「Kotlin File/Class」を選択
![image](https://qiita-image-store.s3.amazonaws.com/0/38174/f36c5ec4-e89a-cb1c-457a-71f0c8dba7c2.png)
### 「New Kotlin File/Class」ダイアログに適当なクラス名を追加
![image](https://qiita-image-store.s3.amazonaws.com/0/38174/ed0ae82c-aea3-cc01-e1cf-e8f0d667f236.png)
### kotlinのクラスが作成される
![image](https://qiita-image-store.s3.amazonaws.com/0/38174/565c603a-acd7-b737-f668-60c15ff1a991.png)

kotlinクラスを以下のように修正

```
package com.example.controller

import org.springframework.stereotype.Component
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.ResponseBody

/**
 *
 */
@Component
@RequestMapping("/demo")
class DemoController {
    @GetMapping("hello")
    @ResponseBody
    fun hello(): String {
        return "hello"
    }
}
```

### JavaのほうのSpringBootのmainクラスを右クリックして、「Run DemoApplication」を選択

![image](https://qiita-image-store.s3.amazonaws.com/0/38174/35a9fb8d-8ac9-a8a7-02f9-ae135f77d50f.png)

#### Spring Bootの起動コンソール

```
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.4.2.RELEASE)

2016-11-20 10:46:08.812  INFO 36216 --- [           main] com.example.DemoApplication              : Starting DemoApplication on softbank221109076128.bbtec.net with PID 36216 (/Users/tgoto/Develop/git/demo/build/classes/main started by tgoto in /Users/tgoto/Develop/git/demo)
2016-11-20 10:46:08.822  INFO 36216 --- [           main] com.example.DemoApplication              : No active profile set, falling back to default profiles: default
2016-11-20 10:46:09.499  INFO 36216 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@7722c3c3: startup date [Sun Nov 20 10:46:09 JST 2016]; root of context hierarchy
2016-11-20 10:46:10.750  INFO 36216 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2016-11-20 10:46:10.762  INFO 36216 --- [           main] o.apache.catalina.core.StandardService   : Starting service Tomcat
2016-11-20 10:46:10.763  INFO 36216 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.6
2016-11-20 10:46:10.841  INFO 36216 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2016-11-20 10:46:10.841  INFO 36216 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1345 ms
2016-11-20 10:46:11.033  INFO 36216 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
2016-11-20 10:46:11.035  INFO 36216 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'metricsFilter' to: [/*]
2016-11-20 10:46:11.036  INFO 36216 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2016-11-20 10:46:11.036  INFO 36216 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2016-11-20 10:46:11.036  INFO 36216 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2016-11-20 10:46:11.036  INFO 36216 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2016-11-20 10:46:11.036  INFO 36216 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'webRequestLoggingFilter' to: [/*]
2016-11-20 10:46:11.036  INFO 36216 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'applicationContextIdFilter' to: [/*]
2016-11-20 10:46:11.402  INFO 36216 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@7722c3c3: startup date [Sun Nov 20 10:46:09 JST 2016]; root of context hierarchy
2016-11-20 10:46:11.476  INFO 36216 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/demo/hello],methods=[GET]}" onto public final java.lang.String com.example.controller.DemoController.hello()
・・・中略・・・
o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/beans || /beans.json],methods=[GET],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2016-11-20 10:46:12.129  INFO 36216 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2016-11-20 10:46:12.301  INFO 36216 --- [           main] o.s.c.support.DefaultLifecycleProcessor  : Starting beans in phase 0
2016-11-20 10:46:12.417  INFO 36216 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2016-11-20 10:46:12.420  INFO 36216 --- [           main] com.example.DemoApplication              : Started DemoApplication in 4.071 seconds (JVM running for 4.458)
```

以下のログがでてればOK

```
2016-11-20 10:46:11.476  INFO 36216 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/demo/hello],methods=[GET]}" onto public final java.lang.String com.example.controller.DemoController.hello()
```

## 起動確認

curlで確認

```
~/D/g/demo ❯❯❯ curl -X GET localhost:8080/demo/hello                                                                                                                                    hello%   
```

heorkuにもデプロイ出来ます。