LoginSignup
10
7

More than 5 years have passed since last update.

KotlinとSpring Boot

Posted at

この記事はKotlin Advent Calendar 2016の23日目の記事です
が、12月23日に書き始めました……果たして間に合うんでしょうか?……

はじめに

Spring BootはJavaでさくっとWebアプリが作れるフレームワークです
もちろんKotlinでも使えますし、公式のページに記事があるので安心です

始め方

Spring InitializrというWeb上でポチポチとボタンを押せば勝手にSpring Bootのプロジェクトファイルを作ってくれるサービスがあるので、これを使うのが一番ラクです
言語の設定はfull versionにする必要があるので、ページ下部のSwitch to the full version.のリンクをクリックすれば項目が出てきます

Switch to the full version.PNG

あとは、LanguageでKotlinを選べばOKです

lang.PNG

あとは各種項目を好きに埋めて、Generate Projectボタンを押して完成です
プロジェクトファイルをzipファイルでダウンロードできます

試しにGradleで作ってみました。設定を確認するとさり気なくKotlinのVerが最新版です。嬉しい

version確認.PNG

あとは好き勝手にKotlinで書いていけばOKです

生成されたコードを読む

Spring BootではSpringBootApplicationアノテーションをつけたクラスを1つ作る必要があるのですが、それもSpring Initializrが自動で生成してくれます

import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication

@SpringBootApplication
open class DemoApplication

fun main(args: Array<String>) {
    SpringApplication.run(DemoApplication::class.java, *args)
}

Spring BootはJavaで使われることを想定しているので、当然といえば当然ですがclassを渡すときはHogeClass::class.javaみたいな書き方をする必要があります

テストコードのサンプルも自動生成されます。初心者に優しい

import org.junit.Test
import org.junit.runner.RunWith
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.context.junit4.SpringRunner

@RunWith(SpringRunner::class)
@SpringBootTest
class DemoApplicationTests {

    @Test
    fun contextLoads() {
    }

}

おわりに

KotlinとSpring BootというかSpring Initializr便利だよね!という話になりました
実際、KotlinとSpring Bootの組み合わせは某社の案件とかでも使っていますが、開発のしやすさとKotlinが入門しやすいのもあって重宝しています
また、AWS Lambdaと組み合わせて、Kotlinで共通ライブラリを作り、そのライブラリをSpring BootとAWS Lambdaから呼び出して使うみたいなこともしています
WebでもKotlin楽しい。そして、かわいい……今後も使っていきたいですね

10
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
7