This post demonstrates how to create a Kotlin-based
Spring Boot
project using IntelliJ IDEA
. It also creates a simple command-line application that leverages Spring
‘s Dependency Injection
.
Requirements
This section lists the Software used for this post.
- Windows 10 Enterprise Edition 64bit
- JDK 8
- IntelliJ IDEA Ultimate 2016.3
- Kotlin version 1.1
Introduction
As Java
developers, we’ve been to a point where we feel Java
codes are too verbose no matter how we refactor existing codes. At times, doing something simple requires too many codes.
With Java 8
, things became a bit better with Streams
, Lambdas
and etc. Still Java
is too verbose. Good thing there are alternatives with Java
. These include Groovy
and Kotlin
.
These languages are concise, safer, 100% interoperable with Java
and tool-friendly.
Spring Boot Project
The following are the steps on how to create a Kotlin-based
Spring Boot
Project.
New Project
To create a new project, go to File -> New -> Project...
This will open the New Project
window. Choose Spring Initialzr
from the left panel and click Next
.
Next, provide some details about the project. Choose Kotlin
as the language.
Next, just click Next
. We select nothing.
Next, provide additional details. Click Finish
when done.
Once done, we’ll have this:
Test Out
We’ll try out by creating a class annotated with @Component
and using that in the main
function.
Bean class
1 2 3 4 5 6 7 8 9 10 11 | package com.turreta.kotlin.sb import org.springframework.stereotype.Component /** * Created by Turreta on 15/6/2017. */ @Component class MyMessageBean { var message: String = "This is your secrete message" } |
Modified main function
In these codes, we retrieved an object of type MyMessageBean
from the Spring Container
and display its content.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | package com.turreta.kotlin.sb import org.springframework.boot.SpringApplication import org.springframework.boot.autoconfigure.SpringBootApplication @SpringBootApplication class ComTurretaKotlinSpringbootApplication fun main(args: Array<String>) { val ctx = SpringApplication.run(ComTurretaKotlinSpringbootApplication::class.java, *args) val msg = ctx.getBean("myMessageBean") as MyMessageBean println(msg.message) } |
Sample Output
Download the Codes
https://github.com/Turreta/Create-a-Kotlin-based-Spring-Boot-project-using-IntelliJ-IDEA