Spring Boot 套餐——使用 Kotlin 开发 SpringBoot

Spring Boot With Kotlin

当前,Spring 5 中已经支持可以使用 Kotlin 来做开发了,那我们就使用 Kotlin 来做一个简单的 CRUD,学习使用 Kotlin 来开发 SpringBoot 的基本套路。
本文主要是一个使用 Kotlin 来编写 SpringBoot 的一个简单 Starter,不牵扯任何底层原理之类的知识,属于教你如何用的 Tutorials。
代码:https://github.com/coding-farmer-ming/spring-boot-with-kotlin

下载基础项目

可以从 https://start.spring.io 下载基础的项目,SpringBoot 的版本选择 2.0.0.M1,编程语言选择 Kotlin,然后生成并使用 IDEA 打开
使用 Kotlin 开发 SpringBoot,需要添加的关于 Kotlin 的依赖有如下两个(在 Spring Start 下载的项目中已经包含这两个依赖):

<dependency>
    <groupId>org.jetbrains.kotlin</groupId>
    <artifactId>kotlin-stdlib-jre8</artifactId>
    <version>1.1.2</version>
</dependency>
<dependency>
    <groupId>org.jetbrains.kotlin</groupId>
    <artifactId>kotlin-reflect</artifactId>
    <version>1.1.2</version>
</dependency>

如果需要使用 Jackson 来做对象转 JSON,需要添加如下依赖:

<dependency>
    <groupId>com.fasterxml.jackson.module</groupId>
    <artifactId>jackson-module-kotlin</artifactId>
    <version>2.8.8</version>
</dependency>

开发 Web 需要添加如下依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

编写简单的 Controller

入门 Hello World

1、首先写一个 Controller,可以命名为 HelloController.kt,然后为该 Controller 添加注解 @RestController,
2、编写第一个方法:

@GetMapping("/hello")
fun helloKotlin(): String {
    return "hello kotlin"
}

启动项目,输入 http://localhost:8080/hello,可以看到已经输出了 hello kotlin

包含一个 Service 的 Hello World

1、首先编写一个 Service,将其命名为 HelloService.kt:

class HelloService {
    fun getHello(): String {
        return "hello kotlin from service"
    }
}

2、改写 HelloController.kt 的声明:

class HelloController(val helloService: HelloService) {}

3、添加一个方法:

@GetMapping("/hello-service")
fun helloKotlinService(): String {
    return helloService.getHello()
}

启动项目,输入 http://localhost:8080/hello-service,可以看到已经输出了 hello kotlin from service

返回一个 DTO 转换的 JSON

1、首先定义一个 DTO,可以命名为 HelloDTO.kt,声明其有一个 greeting 属性:

data class HelloDTO(val greeting: String)

2、在 HelloController.kt 中添加一个方法:

@GetMapping("/hello-dto")
fun helloDTO(): HelloDTO {
    return HelloDTO("hello kotlin from the dto")
}

启动项目,输入 http://localhost:8080/hello-dto,可以看到已经输出了 {"greeting":"hello kotlin from the dto"}

使用数据库来保存数据

1、引入依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
</dependency>

2、数据库配置文件 application.yml:

spring:
  jpa:
    generate-ddl: false
    show-sql: true
    hibernate:
      ddl-auto: none
  datasource:
    platform: h2
    schema: classpath:schema.sql
    data: classpath:data.sql

3、提供 SQL 脚本,分别是 schema.sql 与 data.sql

CREATE TABLE user (
    id bigint NOT NULL AUTO_INCREMENT PRIMARY KEY,
    first_name VARCHAR(50) DEFAULT '' NULL,
    last_name VARCHAR(50) DEFAULT '' NULL
);
insert into user (id, first_name, last_name) values (1, 'zhang', 'san');
insert into user (id, first_name, last_name) values (2, 'li', 'si');
insert into user (id, first_name, last_name) values (3, 'wang', 'wu');

4、编写实体类:

@Entity
class User(
        @Column(name = "first_name") var firstName: String = "",
        @Column(name = "last_name") var lastName: String = "",
        @Id @GeneratedValue(strategy = GenerationType.AUTO) var id: Long = 0)

5、编写 Repository:

@Repository
interface UserRepository: JpaRepository<User, Long> {
    fun findByLastName(name: String): User
}

6、提供 UserController:

@RestController
@RequestMapping("/user")
class UserController(val userRepository: UserRepository) {
    @GetMapping
    fun findAll() = userRepository.findAll()

    @GetMapping("/{name}")
    fun findByLastName(@PathVariable name: String) = userRepository.findByLastName(name)
}

启动项目,输入 http://localhost:8080/userhttp://localhost:8080/san 可以看到对应的结果。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容