8.4 Spring Boot集成Kotlin混合Java开发

本文涉及的产品
云数据库 MongoDB,独享型 2核8GB
推荐场景:
构建全方位客户视图
简介: 8.4 Spring Boot集成Kotlin混合Java开发本章介绍Spring Boot集成Kotlin混合Java开发一个完整的spring boot应用:Restfeel,一个企业级的Rest API接口测试平台(在开源工程restfiddle[1]基础上开发而来)。

8.4 Spring Boot集成Kotlin混合Java开发

本章介绍Spring Boot集成Kotlin混合Java开发一个完整的spring boot应用:Restfeel,一个企业级的Rest API接口测试平台(在开源工程restfiddle[1]基础上开发而来)。

系统技术框架

编程语言:Java,Kotlin

数据库:Mongo

Spring框架:Spring data jpa,Spring data mongodb

前端:jquery,requireJS,

工程构建工具:Gradle

Kotlin简介

Kotlin是一种优雅的语言,是JetBrains公司开发的静态类型JVM语言,与Java无缝集成。与Java相比,Kotlin的语法更简洁、更具表达性,而且提供了更多的特性,比如,高阶函数、操作符重载、字符串模板。它与Java高度可互操作,可以同时用在一个项目中。这门语言的目标是:

  • 创建一种兼容Java的语言
  • 编译速度至少同Java一样快
  • 比Java更安全,能够静态检测常见的陷阱。如:引用空指针
  • 比Java更简洁,通过支持 variable type inference,higher-order functions (closures),extension functions,mixins and first-class delegation 等实现。
  • 比最成熟的竞争者Scala还简单

Kotlin不像Scala另起炉灶,将类库,尤其是集合类都自己来了一遍。kotlin是对现有java的增强,通过扩展方法给java提供了很多诸如fp之类的特性,但同时始终保持对java的兼容。这也是是kotlin官网首页重点强调的:

100% interoperable with Java™。

Kotlin和Scala很像,对于用惯了Scala的人来说用起来很顺手,对于喜欢函数式的开发者,Kotlin是个不错的选择。有个小点,像Groovy动态类型就不用说了,Scala函数最后返回值都可以省去return,但是不晓得为啥Kotlin对return情有独钟。

另外,Kotlin可以编译成Java字节码,也可以编译成JavaScript,在没有JVM的环境运行。

Kotlin创建类的方式与Java类似,比如下面的代码创建了一个有三个属性的Person类:

class Person{
    var name: String = ""
    var age: Int = 0
    var sex: String? = null
}
AI 代码解读

可以看到,Kotlin的变量声明方式略有些不同。在Kotline中,声明变量必须使用关键字var,而如果要创建一个只读/只赋值一次的变量,则需要使用val代替它。

Kotlin对函数式编程的实现恰到好处

一个函数指针的例子:

/**
 * "Callable References" or "Feature Literals", i.e. an ability to pass
 * named functions or properties as values. Users often ask
 * "I have a foo() function, how do I pass it as an argument?".
 * The answer is: "you prefix it with a `::`".
 */

fun main(args: Array<String>) {
    val numbers = listOf(1, 2, 3)
    println(numbers.filter(::isOdd))
}


fun isOdd(x: Int) = x % 2 != 0

AI 代码解读

运行结果: [1, 3]

再看一个复合函数的例子。看了下面的复合函数的例子,你会发现Kotlin的FP的实现相当简洁。(跟纯数学的表达式,相当接近了)

/**
 * The composition function return a composition of two functions passed to it:
 * compose(f, g) = f(g(*)).
 * Now, you can apply it to callable references.
 */

fun main(args: Array<String>) {
    val oddLength = compose(::isOdd, ::length)
    val strings = listOf("a", "ab", "abc")
    println(strings.filter(oddLength))
}

fun isOdd(x: Int) = x % 2 != 0
fun length(s: String) = s.length

fun <A, B, C> compose(f: (B) -> C, g: (A) -> B): (A) -> C {
    return { x -> f(g(x)) }
}

AI 代码解读

运行结果: [a,abc]

简单说明下
val oddLength = compose(::isOdd, ::length)
    val strings = listOf("a", "ab", "abc")
    println(strings.filter(oddLength))
AI 代码解读

这就是数学中,复合函数的定义:

h = h(f(g))

g: A->B
f: B->C
h: A->C

g(A)=B
h(A) = f(B) = f(g(A)) = C
AI 代码解读

只是代码中的写法是:

h=compose( f, g )
h=compose( f(g(A)), g(A) )
AI 代码解读

关于Kotlin,官网有一个非常好的交互式Kotlin学习教程:

http://try.kotlinlang.org/

想深入语言实现细节的,可以直接参考github源码[3]。

Spring Boot集成 Kotlin

1.build.gradle中添加kotlin相关依赖

使用插件

apply {
    plugin "kotlin"
    plugin "kotlin-spring"
    plugin "kotlin-jpa"
    plugin "org.springframework.boot"
    plugin 'java'
    plugin 'eclipse'
    plugin 'idea'
    plugin 'war'
    plugin 'maven'
}

AI 代码解读

构建时插件依赖

buildscript {
    ext {
        kotlinVersion = '1.1.0'
        springBootVersion = '1.5.2.RELEASE'
    }

    dependencies {
        classpath "org.springframework.boot:spring-boot-gradle-plugin:$springBootVersion"
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion"
        classpath "org.jetbrains.kotlin:kotlin-noarg:$kotlinVersion"
        classpath "org.jetbrains.kotlin:kotlin-allopen:$kotlinVersion"
    }

    repositories {
        mavenLocal()
        mavenCentral()
        maven { url "http://oss.jfrog.org/artifactory/oss-release-local" }
        maven { url "http://jaspersoft.artifactoryonline.com/jaspersoft/jaspersoft-repo/" }
        maven { url "https://oss.sonatype.org/content/repositories/snapshots" }

    }
}
AI 代码解读

编译时jar包依赖

dependencies {
    compile("org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion")
    compile("org.jetbrains.kotlin:kotlin-reflect:$kotlinVersion")
    compile("com.fasterxml.jackson.module:jackson-module-kotlin:2.8.4")

    ...

}
AI 代码解读
2.配置源码目录sourceSets
sourceSets {
    main {
        kotlin { srcDir "src/main/kotlin" }
        java { srcDir "src/main/java" }
    }
    test {
        kotlin { srcDir "src/test/kotlin" }
        java { srcDir "src/test/java" }
    }
}
```

指定kotlin,java源码放置目录。让java的归java,Kotlin的归Kotlin。这样区分开来。这个跟scala的插件实现方式上有点区别。scala的插件,是允许你把scala,java代码随便放,插件会自动寻找scala代码编译。


整个工程大目录如下图所示:



![](http://upload-images.jianshu.io/upload_images/1233356-20285f52eb50f486.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)




#####3.写Kotlin代码

Entity实体类

```
package com.restfeel.entity

import org.bson.types.ObjectId
import org.springframework.data.mongodb.core.mapping.Document
import java.util.*
import javax.persistence.GeneratedValue
import javax.persistence.GenerationType
import javax.persistence.Id
import javax.persistence.Version

@Document(collection = "blog") // 如果不指定collection,默认遵从命名规则
class Blog {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    var id: String = ObjectId.get().toString()
    @Version
    var version: Long = 0
    var title: String = ""
    var content: String = ""
    var author: String = ""
    var gmtCreated: Date = Date()
    var gmtModified: Date = Date()
    var isDeleted: Int = 0 //1 Yes 0 No
    var deletedDate: Date = Date()
    override fun toString(): String {
        return "Blog(id='$id', version=$version, title='$title', content='$content', author='$author', gmtCreated=$gmtCreated, gmtModified=$gmtModified, isDeleted=$isDeleted, deletedDate=$deletedDate)"
    }

}


```

Service类

```
package com.restfeel.service

import com.restfeel.entity.Blog
import org.springframework.data.mongodb.repository.MongoRepository
import org.springframework.data.mongodb.repository.Query
import org.springframework.data.repository.query.Param

interface BlogService : MongoRepository<Blog, String> {

    @Query("{ 'title' : ?0 }")
    fun findByTitle(@Param("title") title: String): Iterable<Blog>

}

```


Controller类

```
package com.restfeel.controller

import com.restfeel.entity.Blog
import com.restfeel.service.BlogService
import org.springframework.boot.autoconfigure.EnableAutoConfiguration
import org.springframework.context.annotation.ComponentScan
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.stereotype.Controller
import org.springframework.transaction.annotation.Propagation
import org.springframework.transaction.annotation.Transactional
import org.springframework.ui.Model
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.ResponseBody
import java.util.*
import javax.servlet.http.HttpServletRequest

/**
 * 文章列表,写文章的Controller
 * @author Jason Chen  2017/3/31 01:10:16
 */

@Controller
@EnableAutoConfiguration
@ComponentScan
@Transactional(propagation = Propagation.REQUIRES_NEW)
class BlogController(val blogService: BlogService) {
    @GetMapping("/blogs.do")
    fun listAll(model: Model): String {
        val authentication = SecurityContextHolder.getContext().authentication
        model.addAttribute("currentUser", if (authentication == null) null else authentication.principal as UserDetails)
        val allblogs = blogService.findAll()
        model.addAttribute("blogs", allblogs)
        return "jsp/blog/list"
    }

    @PostMapping("/saveBlog")
    @ResponseBody
    fun saveBlog(blog: Blog, request: HttpServletRequest):Blog {
        blog.author = (request.getSession().getAttribute("currentUser") as UserDetails).username
        return blogService.save(blog)
    }

    @GetMapping("/goEditBlog")
    fun goEditBlog(@RequestParam(value = "id") id: String, model: Model): String {
        model.addAttribute("blog", blogService.findOne(id))
        return "jsp/blog/edit"
    }

    @PostMapping("/editBlog")
    @ResponseBody
    fun editBlog(blog: Blog, request: HttpServletRequest) :Blog{
        blog.author = (request.getSession().getAttribute("currentUser") as UserDetails).username
        blog.gmtModified = Date()
        blog.version = blog.version + 1
        return blogService.save(blog)
    }

    @GetMapping("/blog")
    fun blogDetail(@RequestParam(value = "id") id: String, model: Model): String {
        model.addAttribute("blog", blogService.findOne(id))
        return "jsp/blog/detail"
    }

    @GetMapping("/listblogs")
    @ResponseBody
    fun listblogs(model: Model) = blogService.findAll()

    @GetMapping("/findBlogByTitle")
    @ResponseBody
    fun findBlogByTitle(@RequestParam(value = "title") title: String) = blogService.findByTitle(title)

}

```



对应的前端代码,这里就不多说了。可以参考工程源代码[4]。



SpringBoot的启动类: 我们用Kotlin写SpringBoot的启动类:

```
package com.restfeel

import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.CommandLineRunner
import org.springframework.boot.SpringApplication
import org.springframework.core.env.Environment

/**
 * Created by jack on 2017/3/29.
 * @author jack
 * @date 2017/03/29
 */
@RestFeelBoot
class RestFeelApplicationKotlin : CommandLineRunner {
    @Autowired
    private val env: Environment? = null

    override fun run(vararg args: String?) {
        println("RESTFEEL 启动完毕")
        println("应用地址:" + env?.getProperty("application.host-uri"))
    }
}

fun main(args: Array<String>) {
    SpringApplication.run(RestFeelApplicationKotlin::class.java, *args)
}



```



其中,@RestFeelBoot是自定义注解,代码如下:

```
package com.restfeel;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

/**
 * Created by jack on 2017/3/23.
 *
 * @author jack
 * @date 2017/03/23
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Configuration
@EnableAutoConfiguration
@ComponentScan
public @interface RestFeelBoot {
    Class<?>[] exclude() default {};
}

```


#####运行测试

命令行输入gradle bootRun,运行应用。 访问 http://127.0.0.1:5678/blogs.do 

文章列表
![](http://upload-images.jianshu.io/upload_images/1233356-365b79713f187cc3.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)




写文章

![](http://upload-images.jianshu.io/upload_images/1233356-87929f0b83a43ad8.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

阅读文章



![](http://upload-images.jianshu.io/upload_images/1233356-4b12e505588c6b3f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)




##小结

本章示例工程源代码:

https://github.com/Jason-Chen-2017/restfeel/tree/restfeel_kotlin_2017.5.6




参考资料:
1.https://github.com/AnujaK/restfiddle
2.http://www.jianshu.com/c/498ebcfd27ad
3.https://github.com/JetBrains/kotlin
4.https://github.com/Jason-Chen-2017/restfeel/tree/restfeel_kotlin_2017.5.6
AI 代码解读
相关实践学习
MongoDB数据库入门
MongoDB数据库入门实验。
快速掌握 MongoDB 数据库
本课程主要讲解MongoDB数据库的基本知识,包括MongoDB数据库的安装、配置、服务的启动、数据的CRUD操作函数使用、MongoDB索引的使用(唯一索引、地理索引、过期索引、全文索引等)、MapReduce操作实现、用户管理、Java对MongoDB的操作支持(基于2.x驱动与3.x驱动的完全讲解)。 通过学习此课程,读者将具备MongoDB数据库的开发能力,并且能够使用MongoDB进行项目开发。 &nbsp; 相关的阿里云产品:云数据库 MongoDB版 云数据库MongoDB版支持ReplicaSet和Sharding两种部署架构,具备安全审计,时间点备份等多项企业能力。在互联网、物联网、游戏、金融等领域被广泛采用。 云数据库MongoDB版(ApsaraDB for MongoDB)完全兼容MongoDB协议,基于飞天分布式系统和高可靠存储引擎,提供多节点高可用架构、弹性扩容、容灾、备份回滚、性能优化等解决方案。 产品详情: https://www.aliyun.com/product/mongodb
目录
打赏
0
0
0
0
78
分享
相关文章
Java也能快速搭建AI应用?一文带你玩转Spring AI可落地性
Java语言凭借其成熟的生态与解决方案,特别是通过 Spring AI 框架,正迅速成为 AI 应用开发的新选择。本文将探讨如何利用 Spring AI Alibaba 构建在线聊天 AI 应用,并实现对其性能的全面可观测性。
【YashanDB知识库】yasdb jdbc驱动集成BeetISQL中间件,业务(java)报autoAssignKey failure异常
在BeetISQL 2.13.8版本中,客户使用batch insert向yashandb表插入数据并尝试获取自动生成的sequence id时,出现类型转换异常。原因是beetlsql在prepareStatement时未指定返回列,导致yashan JDBC驱动返回rowid(字符串),与Java Bean中的数字类型tid不匹配。此问题影响业务流程,使无法正确获取sequence id。解决方法包括:1) 在batchInsert时不返回自动生成的sequence id;2) 升级至BeetISQL 3,其已修正该问题。
【YashanDB知识库】yasdb jdbc驱动集成BeetISQL中间件,业务(java)报autoAssignKey failure异常
Spring 集成 DeepSeek 的 3大方法(史上最全)
DeepSeek 的 API 接口和 OpenAI 是兼容的。我们可以自定义 http client,按照 OpenAI 的rest 接口格式,去访问 DeepSeek。自定义 Client 集成DeepSeek ,可以通过以下步骤实现。步骤 1:准备工作访问 DeepSeek 的开发者平台,注册并获取 API 密钥。DeepSeek 提供了与 OpenAI 兼容的 API 端点(例如),确保你已获取正确的 API 地址。
Spring 集成 DeepSeek 的 3大方法(史上最全)
Java||Springboot读取本地目录的文件和文件结构,读取服务器文档目录数据供前端渲染的API实现
博客不应该只有代码和解决方案,重点应该在于给出解决方案的同时分享思维模式,只有思维才能可持续地解决问题,只有思维才是真正值得学习和分享的核心要素。如果这篇博客能给您带来一点帮助,麻烦您点个赞支持一下,还可以收藏起来以备不时之需,有疑问和错误欢迎在评论区指出~
Java||Springboot读取本地目录的文件和文件结构,读取服务器文档目录数据供前端渲染的API实现
【YashanDB知识库】yasdb jdbc驱动集成druid连接池,业务(java)日志中有token IDENTIFIER start异常
客户Java日志中出现异常,影响Druid的merge SQL功能(将SQL字面量替换为绑定变量以统计性能),但不影响正常业务流程。原因是Druid在merge SQL时传入null作为dbType,导致无法解析递归查询中的`start`关键字。
Java 也能快速搭建 AI 应用?一文带你玩转 Spring AI 可观测性
Java 也能快速搭建 AI 应用?一文带你玩转 Spring AI 可观测性
支持 40+ 插件,Spring AI Alibaba 简化智能体私有数据集成
通过使用社区官方提供的超过 20 种 RAG 数据源和 20 种 Tool Calling 接口,开发者可以轻松接入多种外部数据源(如 GitHub、飞书、云 OSS 等)以及调用各种工具(如天气预报、地图导航、翻译服务等)。这些默认实现大大简化了智能体的开发过程,使得开发者无需从零开始,便可以快速构建功能强大的智能体系统。通过这种方式,智能体不仅能够高效处理复杂任务,还能适应各种应用场景,提供更加智能、精准的服务。
|
2月前
|
使用Java和Spring Data构建数据访问层
本文介绍了如何使用 Java 和 Spring Data 构建数据访问层的完整过程。通过创建实体类、存储库接口、服务类和控制器类,实现了对数据库的基本操作。这种方法不仅简化了数据访问层的开发,还提高了代码的可维护性和可读性。通过合理使用 Spring Data 提供的功能,可以大幅提升开发效率。
82 21
java spring 项目若依框架启动失败,启动不了服务提示端口8080占用escription: Web server failed to start. Port 8080 was already in use. Action: Identify and stop the process that’s listening on port 8080 or configure this application to listen on another port-优雅草卓伊凡解决方案
java spring 项目若依框架启动失败,启动不了服务提示端口8080占用escription: Web server failed to start. Port 8080 was already in use. Action: Identify and stop the process that’s listening on port 8080 or configure this application to listen on another port-优雅草卓伊凡解决方案
75 7
SaaS云计算技术的智慧工地源码,基于Java+Spring Cloud框架开发
智慧工地源码基于微服务+Java+Spring Cloud +UniApp +MySql架构,利用传感器、监控摄像头、AI、大数据等技术,实现施工现场的实时监测、数据分析与智能决策。平台涵盖人员、车辆、视频监控、施工质量、设备、环境和能耗管理七大维度,提供可视化管理、智能化报警、移动智能办公及分布计算存储等功能,全面提升工地的安全性、效率和质量。