In the tutorial, Kotlination will show you the first step to build a SpringBoot Kotlin RESTful Web Service.
Related posts:
– How to start Kotlin development with SpringBoot + Maven + SpringToolSuite
– Kotlin – Spring JPA + Postgresql | Spring Boot Example
>>> Refer at: JavaSampleApproach.com
I. Technologies
– Java 1.8
– Maven 3.3.9
– Spring Tool Suite – Version 3.8.1.RELEASE
– SpringBoot – 1.5.6.RELEASE
– Kotlin 1.4
II. SpringBoot Kotlin RESTful Web Service
SpringBoot supports us a lots for build a RESTful Web Service with @RestController
annotation:
1 2 3 4 5 |
[...] @RestController class KotlinRestController { ... } |
For use it, we need a spring-boot-starter-web
dependency.
By default, SpringBoot starts an embedded Tomcat container at port: 8080. We can use server.port
in application.properties to change the default.
III. Practice
In the tutorial, we create a SpringBoot project as below image:
Step to do:
– Create SpringBoot project
– Create model data
– Create RestController
– Run and Check results
1. Create SpringBoot project
Using SpringToolSuite to create a SpringBoot project.
>>> Refer more at: How to start Kotlin development with SpringBoot + Maven + SpringToolSuite
Then add needed dependency:
1 2 3 4 |
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> |
2. Create model data
– Create a Customer
data model:
1 2 3 4 5 6 7 |
package com.kotlination.restful.model data class Customer( val firstName: String, val lastName: String, val age: Int) { } |
3. Create RestController
– Create a RestController:
1 2 3 4 5 6 7 8 9 10 11 12 |
package com.kotlination.restful.controller import com.kotlination.restful.model.Customer import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.RestController @RestController class KotlinRestController { @GetMapping("/customer") fun getCustomer() = Customer("Jack", "Smith", 25) } |
Open application.properties file, we can modified Tomcat server port:
1 |
server.port=8081 |
4. Run and Check results
Build and Run the SpringBoot project as commandlines {mvn clean install
, mvn spring-boot:run
}.
Make a request http://localhost:8081/customer