使用Kotlin + Spring Boot创建一个Hello! World!的应用程序
项目创建
使用Spring Initializr创建项目
https://start.spring.io/
请按照下图所示进行选择。
Gradle:构建工具
Kotlin:编程语言
Spring Boot 2.1.6:框架版本
Spring Web Starter:Web 开发起始器

最后,点击“生成项目”,开始下载Zip文件。
解压后,将会出现按照上述指定创建的项目文件夹。

当您打开IDE时,将开始加载项目。点击”导入Gradle项目”选项。



考试进行

在这种状态下,没有特别的变化,但8080端口上的Web服务器正在运行。
http://localhost:8080/
访问时显示错误页面。


新增REST API
创建控制器

在这里,我们需要添加import和@GetMapping注解。
这是一个只返回字符串的简单get方法。
package com.example.swagger.demo
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RestController
@RestController
class HelloController {
@GetMapping("/hello")
fun hello(): String {
return "Hello! World!"
}
}
再次运行并访问以下地址:
http://localhost:8080/hello

添加RequestParam
因为觉得这样太孤单了,所以我会尝试将参数传递给控制器。
添加RequestMapping和RequestParam。
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
在HelloController中添加@RequestMapping注解,并按照以下方式进行设置。
package com.example.swagger.demo
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
@RestController
@RequestMapping
class HelloController {
@GetMapping("/hello")
fun hello(@RequestParam(value = "name", required = false, defaultValue = "world") name: String): String {
return "Hello, $name!"
}
}
请再次执行,并访问以下网址:
http://localhost:8080/hello?name=taro


请参考
使用Kotlin和Spring构建API和文档 – Qiita