kotlin配合springboot开发web

一、使用maven创建springboot项目

引入springboot依赖


        org.springframework.boot
        spring-boot-starter-parent
        2.2.0.RELEASE
         


    
        1.8
        1.3.50
    

    
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.projectlombok
            lombok
            true
        
        
            org.springframework.boot
            spring-boot-starter-jdbc
        
        
            mysql
            mysql-connector-java
            5.1.48
        
        
            com.alibaba
            druid
            1.1.20
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
            
                
                    org.junit.vintage
                    junit-vintage-engine
                
            
        
        
            junit
            junit
            test
        
        
            com.alibaba
            fastjson
            1.2.48
        
    

再加入kotlin的依赖及plugins

        
            org.jetbrains.kotlin
            kotlin-stdlib-jdk8
        
        
            org.jetbrains.kotlin
            kotlin-reflect
        
        
            org.jetbrains.kotlin
            kotlin-stdlib
        
        
            com.fasterxml.jackson.module
            jackson-module-kotlin
        


        ${project.basedir}/src/main/java
        ${project.basedir}/src/test/java
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
            
                kotlin-maven-plugin
                org.jetbrains.kotlin
                
                    
                        -Xjsr305=strict
                    
                    
                        spring
                        jpa
                        all-open
                    
                    
                        
                    
                
                
                    
                        kapt
                        
                            kapt
                        
                        
                            
                                src/main/kotlin
                            
                            
                                
                                    org.springframework.boot
                                    spring-boot-configuration-processor
                                    ${project.parent.version}
                                
                            
                        
                    
                
            
        
    

二、准备数据库脚本

CREATE DATABASE /*!32312 IF NOT EXISTS*/`springboot_db` /*!40100 DEFAULT CHARACTER SET utf8 */;

USE `springboot_db`;

DROP TABLE IF EXISTS `t_author`;

CREATE TABLE `t_author` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '用户ID',
  `real_name` varchar(32) NOT NULL COMMENT '用户名称',
  `nick_name` varchar(32) NOT NULL COMMENT '用户匿名',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

三、实体类

package cn.baiyu.test.entity

/**
@author baiyu
@data 2019-10-28 14:41
 */
class Author {
    var id: Long? = null
    var realName: String? = null
    var nickName: String? = null
}

四、dao

package cn.baiyu.test.dao

import cn.baiyu.test.entity.Author

/**
@author baiyu
@data 2019-10-28 14:42
 */
interface AuthorDao {
    fun add(author: Author): Int
    fun update(author: Author): Int
    fun delete(id: Long): Int
    fun findAuthor(id: Long): Author?
    fun findAuthorList(): List
}

dao的实现

package cn.baiyu.test.dao.impl

import cn.baiyu.test.dao.AuthorDao
import cn.baiyu.test.entity.Author
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.jdbc.core.BeanPropertyRowMapper
import org.springframework.jdbc.core.JdbcTemplate
import org.springframework.stereotype.Repository

/**
@author baiyu
@data 2019-10-28 14:45
 */
@Repository
open class AuthorDaoImpl : AuthorDao {

    @Autowired
    private lateinit var jdbcTemplate: JdbcTemplate

    override fun add(author: Author): Int {
        return jdbcTemplate.update("insert into t_author(real_name, nick_name) values(?, ?)",
                author.realName, author.nickName)
    }

    override fun update(author: Author): Int {
        return jdbcTemplate.update("update t_author set real_name = ?, nick_name = ? where id = ?",
                *arrayOf(author.realName, author.nickName, author.id))
    }

    override fun delete(id: Long): Int {
        return jdbcTemplate.update("delete from t_author where id = ?", id)
    }

    override fun findAuthor(id: Long): Author? {
        val list = jdbcTemplate.query("select * from t_author where id = ?",
                arrayOf(id), BeanPropertyRowMapper(Author::class.java))
        return list?.get(0);
    }

    override fun findAuthorList(): List {
        return jdbcTemplate.query("select * from t_author", arrayOf(), BeanPropertyRowMapper(Author::class.java))
    }
}

五、service接口

package cn.baiyu.test.service

import cn.baiyu.test.entity.Author

/**
@author baiyu
@data 2019-10-28 14:45
 */
interface AuthorService {
    fun add(author: Author): Int
    fun update(author: Author): Int
    fun delete(id: Long): Int
    fun findAuthor(id: Long): Author?
    fun findAuthorList(): List
}

service接口的实现

package cn.baiyu.test.service.impl

import cn.baiyu.test.dao.AuthorDao
import cn.baiyu.test.entity.Author
import cn.baiyu.test.service.AuthorService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service

/**
@author baiyu
@data 2019-10-28 14:46
 */
@Service("authorService")
open class AuthorServiceImpl : AuthorService {

    @Autowired
    private lateinit var authorDao: AuthorDao

    override fun update(author: Author): Int {
        return this.authorDao.update(author)
    }

    override fun add(author: Author): Int {
        return this.authorDao.add(author)
    }

    override fun delete(id: Long): Int {
        return this.authorDao.delete(id)
    }

    override fun findAuthor(id: Long): Author? {
        return this.authorDao.findAuthor(id)
    }

    override fun findAuthorList(): List {
        return this.authorDao.findAuthorList()
    }
}

六、controller

package cn.baiyu.test.controller

import cn.baiyu.test.entity.Author
import cn.baiyu.test.service.AuthorService
import com.alibaba.fastjson.JSONObject
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.*
import javax.servlet.http.HttpServletRequest

/**
@author baiyu
@data 2019-10-28 14:47
 */
@RestController
@RequestMapping(value = ["/authors"])
class AuthorController {

    @Autowired
    private lateinit var authorService: AuthorService

    /**
     * 查询用户列表
     */
    @RequestMapping(method = [RequestMethod.GET])
    fun getAuthorList(request: HttpServletRequest): Map {
        val authorList = this.authorService.findAuthorList()
        val param = HashMap()
        param["total"] = authorList.size
        param["rows"] = authorList
        return param
    }

    /**
     * 查询用户信息
     */
    @RequestMapping(value = ["/{userId:\\d+}"], method = [RequestMethod.GET])
    fun getAuthor(@PathVariable userId: Long, request: HttpServletRequest): Author {
        return authorService.findAuthor(userId) ?: throw RuntimeException("查询错误")
    }

    /**
     * 新增方法
     */
    @RequestMapping(method = [RequestMethod.POST])
    fun add(@RequestBody jsonObject: JSONObject) {
        val userId = jsonObject.getString("user_id")
        val realName = jsonObject.getString("real_name")
        val nickName = jsonObject.getString("nick_name")

        val author = Author()
        author.id = java.lang.Long.valueOf(userId)
        author.realName = realName
        author.nickName = nickName
        try {
            this.authorService.add(author)
        } catch (e: Exception) {
            throw RuntimeException("新增错误")
        }
    }

    /**
     * 更新方法
     */
    @RequestMapping(value = ["/{userId:\\d+}"], method = [RequestMethod.PUT])
    fun update(@PathVariable userId: Long, @RequestBody jsonObject: JSONObject) {
        var author = this.authorService.findAuthor(userId)
        val realName = jsonObject.getString("real_name")
        val nickName = jsonObject.getString("nick_name")
        try {
            if (author != null) {
                author.realName = realName
                author.nickName = nickName
                this.authorService.update(author)
            }
        } catch (e: Exception) {
            throw RuntimeException("更新错误")
        }

    }

    /**
     * 删除方法
     */
    @RequestMapping(value = ["/{userId:\\d+}"], method = [RequestMethod.DELETE])
    fun delete(@PathVariable userId: Long) {
        try {
            this.authorService.delete(userId)
        } catch (e: Exception) {
            throw RuntimeException("删除错误")
        }
    }
}

七、启动类

package cn.baiyu.test

import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication

/**
@author baiyu
@data 2019-10-28 14:52
 */
@SpringBootApplication
class SpringBootKotlinIntegration

fun main(args: Array) {
    runApplication(*args)
}

八、配置文件

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springboot_db?useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.username=root
spring.datasource.password=root

九、启动测试

kotlinDemo

demo of springboot with lotlin
关于测试
这里,笔者推荐 IDEA 的 Editor REST Client。IDEA 的 Editor REST Client 在 IntelliJ IDEA 2017.3 版本就开始支持,在 2018.1 版本添加了很多的特性。

### 查询用户列表
GET http://localhost:8080/authors
Accept : application/json
Content-Type : application/json;charset=UTF-8
 
### 查询用户信息
GET http://localhost:8080/authors/15
Accept : application/json
Content-Type : application/json;charset=UTF-8
 
### 新增方法
POST http://localhost:8080/authors
Content-Type: application/json
 
{
    "user_id": "21",
    "real_name": "梁桂钊",
    "nick_name": "梁桂钊"
}
 
### 更新方法
PUT http://localhost:8080/authors/21
Content-Type: application/json
 
{
    "real_name" : "lianggzone",
    "nick_name": "lianggzone"
}
 
### 删除方法
DELETE http://localhost:8080/authors/21
Accept : application/json
Content-Type : application/json;charset=UTF-8

总结
通过,上面这个简单的案例,我们发现 Spring Boot 整合 Kotlin 非常容易,并简化 Spring 应用的初始搭建以及开发过程。

你可能感兴趣的:(kotlin配合springboot开发web)