Let’s create an application with Kotlin and Spring. Spring is a highly sophisticated framework in Java, which can do almost everything.
Environment
Kotlin and Spring. And kotlinx.html for view. (Thymeleaf can be used, too.) Project structure is managed by Gradle. Intellij IDEA Community Edition for the editor.
- Gradle 4.4
- Kotlin 1.2.0
- kotlinx.html 0.6.6
- Spring Boot 1.5.8
- PostgreSQL 9.5.6
- Intellij IDEA 2017.2.6 (Community Edition)
- Kotlin Plugin 1.2.0-release-IJ2017.2-1
- OpenJDK 1.8
The version of Kotlin plugin can be checked in Intellij IDEA menu, Tools -> Kotlin -> Configure kotlin Plugin Updates.
Create the application base
Build the project with the wizard in Intellij IDEA. At the left pane in New Project dialog, select “Gradle” and check “Kotlin (Java)” and push “Next” button. “Multiplatform” shown in the dialog is trial feature from Kotlin 1.2.0, which is for cross compilation, but this time we don’t use it.
GroupId, ArtifactId are to be “com.example”, “myapp”
Now the file “build.gradle” is as follows.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
group 'com.example' version '1.0-SNAPSHOT' buildscript { ext.kotlin_version = '1.2.0' repositories { mavenCentral() } dependencies { classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } } apply plugin: 'kotlin' repositories { mavenCentral() } dependencies { compile "org.jetbrains.kotlin:kotlin-stdlib-jre8:$kotlin_version" } compileKotlin { kotlinOptions.jvmTarget = "1.8" } compileTestKotlin { kotlinOptions.jvmTarget = "1.8" } |
If the version of Gradle Wrapper is less than 4.4, please upgrade it by executing ./gradlew wrapper --gradle-version=4.4
. The version of Gradle Wrapper can be checked by executing ./gradlew -v
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
% ./gradlew -v ------------------------------------------------------------ Gradle 4.4 ------------------------------------------------------------ Build time: 2017-12-06 09:05:06 UTC Revision: cf7821a6f79f8e2a598df21780e3ff7ce8db2b82 Groovy: 2.4.12 Ant: Apache Ant(TM) version 1.9.9 compiled on February 2 2017 JVM: 1.8.0_151 (Oracle Corporation 25.151-b12) OS: Linux 4.10.0-40-generic amd64 |
build.gradle
の dependencies
に compile("org.springframework.boot:spring-boot-starter-web:1.5.8.RELEASE")
を追加します。
Create Application class and create main method of Spring Boot.
1 2 3 4 5 |
src - main - kotlin - com.example.myapp - Application.kt |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
package com.example.myapp import org.springframework.boot.SpringApplication import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.web.support.SpringBootServletInitializer @SpringBootApplication open class Application: SpringBootServletInitializer() { companion object { @JvmStatic fun main(args: Array<String>) { SpringApplication.run(Application::class.java, *args) } } } |
Then, the serve can work.
Continues to Kotlin 1.2.0 + Spring: create Web Application (2 of 4)