Spring Boot和Kotlin的无缝整合与完美交融

作者:梁桂钊 时间:2022-07-08 04:54:09 

目录
  • 环境依赖

  • 数据源

    • 方案一 使用 Spring Boot 默认配置

    • 方案二 手动创建

  • 脚本初始化

    • 使用 JdbcTemplate 操作

      • 实体对象

      • DAO相关

      • Service相关

      • Controller相关

    • 关于测试

      • 总结

        前言

        本文讲解 Spring Boot2 基础下,如何使用 Kotlin,并无缝整合与完美交融。为了让读者更加熟悉 Kotlin 的语法糖,笔者会在未来的几篇文章中,聊聊 Kotlin 的新特性及其语法糖。下面话不多说了,来一起看看详细的介绍吧

        环境依赖

        修改 POM 文件,添加 spring boot 依赖。


        紧接着,我们需要添加 mysql 依赖。


        最后,添加 Kotlin 依赖。


        注意的是,在 Kotlin 中,data class 默认没有无参构造方法,并且 data class 默认为 final 类型,不可以被继承。注意的是,如果我们使用 Spring + Kotlin 的模式,那么使用 @autowared 就可能遇到这个问题。因此,我们可以添加 NoArg 为标注的类生成无参构造方法。使用 AllOpen 为被标注的类去掉 final,允许被继承。


        至此,我们 Maven 的依赖环境大致配置完毕。

        数据源

        方案一 使用 Spring Boot 默认配置

        使用 Spring Boot 默认配置,不需要在创建 dataSource 和 jdbcTemplate 的 Bean。

        在 src/main/resources/application.properties 中配置数据源信息。


        spring.datasource.driver-class-name=com.mysql.jdbc.Driver
        spring.datasource.url=jdbc:mysql://localhost:3307/springboot_db
        spring.datasource.username=root
        spring.datasource.password=root

        方案二 手动创建

        在 src/main/resources/config/source.properties 中配置数据源信息。


        # mysql
        source.driverClassName = com.mysql.jdbc.Driver
        source.url = jdbc:mysql://localhost:3306/springboot_db
        source.username = root
        source.password = root

        这里, 创建 dataSource 和jdbcTemplate。


        @Configuration
        @EnableTransactionManagement
        @PropertySource(value = *arrayOf("classpath:config/source.properties"))
        open class BeanConfig {
        @Autowired
        private lateinit var env: Environment
        @Bean
        open fun dataSource(): DataSource {
        val dataSource = DruidDataSource()
        dataSource.driverClassName = env!!.getProperty("source.driverClassName").trim()
        dataSource.url = env.getProperty("source.url").trim()
        dataSource.username = env.getProperty("source.username").trim()
        dataSource.password = env.getProperty("source.password").trim()
        return dataSource
        }
        @Bean
        open fun jdbcTemplate(): JdbcTemplate {
        val jdbcTemplate = JdbcTemplate()
        jdbcTemplate.dataSource = dataSource()
        return jdbcTemplate
        }
        }

        脚本初始化

        先初始化需要用到的 SQL 脚本。


        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;

        使用 JdbcTemplate 操作

        实体对象


        class Author {
        var id: Long? = null
        var realName: String? = null
        var nickName: String? = null
        }

        DAO相关


        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

        我们来定义实现类,通过 JdbcTemplate 定义的数据访问操作。


        @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

        Service相关


        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 层调用 Dao 层的方法,这个是典型的套路。


        @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

        Controller相关

        为了展现效果,我们先定义一组简单的 RESTful API 接口进行测试。


        @RestController
        @RequestMapping(value = "/authors")
        class AuthorController {
        @Autowired
        private lateinit var authorService: AuthorService
        /**
        * 查询用户列表
        */
        @RequestMapping(method = [RequestMethod.GET])
        fun getAuthorList(request: HttpServletRequest): Map

        最后,我们通过 SpringKotlinApplication 运行程序。


        @SpringBootApplication(scanBasePackages = ["com.lianggzone.demo.kotlin"])
        open class SpringKotlinApplication{
        fun main(args: Array

        关于测试

        这里,笔者推荐 IDEA 的 Editor REST Client。IDEA 的 Editor REST Client 在 IntelliJ IDEA 2017.3 版本就开始支持,在 2018.1 版本添加了很多的特性。事实上,它是 IntelliJ IDEA 的 HTTP Client 插件。参见笔者之前的另一篇文章: 快速测试 API 接口的新技能


        ### 查询用户列表
        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 的语法糖,笔者会在未来的几篇文章中,聊聊 Kotlin 的新特性及其语法糖。

        来源:http://blog.720ui.com/2018/springboot2_kotlin_prime/

        标签:kotlin,spring,boot
        0
        投稿

        猜你喜欢

      • 自定义类加载器以及打破双亲委派模型解析

        2023-06-22 22:03:59
      • Java 8 中 Function 接口使用方法介绍

        2022-12-08 23:54:39
      • Java事务管理学习之Spring和Hibernate详解

        2023-04-11 00:01:25
      • 聊聊Java 中的线程中断

        2021-05-31 02:04:30
      • Android如何让WebView中的HTML5页面实现视频全屏播放

        2023-07-29 00:32:06
      • java判断字符串是否为数字的方法小结

        2023-11-25 05:54:52
      • Java线程池ThreadPoolExecutor原理及使用实例

        2022-04-30 05:53:00
      • 你所不知道的Spring自动注入详解

        2021-09-04 19:30:08
      • Java常见数据结构面试题(带答案)

        2023-11-24 19:44:05
      • Java面向对象基础,类,变量,方法

        2023-04-08 13:21:49
      • Java Mybatis框架Dao层的实现与映射文件以及核心配置文件详解分析

        2021-06-15 16:29:22
      • java模拟TCP通信实现客户端上传文件到服务器端

        2023-11-26 10:14:49
      • Spring Cloud + Nacos + Seata整合过程(分布式事务解决方案)

        2021-08-31 04:26:52
      • Java PreparedStatement用法详解

        2023-08-08 20:20:51
      • Java线程创建的四种方式总结

        2023-10-29 19:36:03
      • SpringCloud之微服务容错的实现

        2023-11-29 02:02:22
      • Java异常处理机制try catch流程详解

        2022-09-23 08:51:09
      • Java 求解如何把二叉搜索树转换为累加树

        2021-11-19 14:09:54
      • 浅谈MyBatis通用Mapper实现原理

        2022-11-18 18:45:16
      • Java实现五子棋游戏的完整代码

        2022-07-01 15:32:34
      • asp之家 软件编程 m.aspxhome.com