Kotlin是一门最近比较流行的静态类型编程语言,并且和Groovy、Scala同样同属Java系。Kotlin具备的不少静态语言特性诸如:类型判断、多范式、扩展函数、模式匹配等等让我没法只做为一个吃瓜群众了,因此稍微花了点时间了解了一下该语言。java
本文主要介绍一下如何使用Kotlin结合SpringBt开发一个带有数据库交互的REST风格基本程序mysql
注: 本文首发于 My 公众号 CodeSheep ,可 长按 或 扫描 下面的 当心心 来订阅 ↓ ↓ ↓web
没啥好说的,我这里建立的是基于Gradle的Kotlin工程:spring
建立完成后的基本工程样式和SpringBt的工程几乎没任何区别,给张图示意一下好了:sql
好啦,接下来咱们就来写代码完善这个工程便可数据库
咱们须要在build.gradle中引入SpringBt依赖,除此以外还要引入一些特定的插件方便咱们向写Java代码同样来写Kotlin程序!编程
在dependencies中加入以下依赖:c#
dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib-jre8:$kotlin_version"
testCompile group: 'junit', name: 'junit', version: '4.12'
compile("org.springframework.boot:spring-boot-starter-web")
testCompile("org.springframework.boot:spring-boot-starter-test")
compile("org.springframework.boot:spring-boot-starter-data-jpa")
compile('mysql:mysql-connector-java:5.1.13')
}
复制代码
这样SpringBt相关的依赖就配置上了!springboot
接下来咱们配置两个很是关键的插件依赖:bash
咱们先配上,等下解释:
buildscript {
ext.kotlin_version = '1.1.1'
ext.springboot_version = '1.5.2.RELEASE'
repositories {
mavenCentral()
}
dependencies {
// Kotlin Gradle插件
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
// SpringBoot Gradle插件
classpath("org.springframework.boot:spring-boot-gradle-plugin:$springboot_version")
// Kotlin整合SpringBoot的默认无参构造函数,默认把全部的类设置open类插件
classpath("org.jetbrains.kotlin:kotlin-noarg:$kotlin_version") // 无参插件
classpath("org.jetbrains.kotlin:kotlin-allopen:$kotlin_version") // 全开放插件
}
}
复制代码
其中(如下解释源自《Kotlin极简教程》):
org.jetbrains.kotlin:kotlin-noarg是无参(no-arg)编译器插件,它为具备特定注解的类生成一个额外的零参数构造函数。 这个生成的构造函数是合成的,所以不能从 Java 或 Kotlin 中直接调用,但可使用反射调用。 这样咱们就可使用 Java Persistence API(JPA)实例化 data 类。
org.jetbrains.kotlin:kotlin-allopen 是全开放编译器插件。咱们使用Kotlin 调用Java的Spring AOP框架和库,须要类为 open(可被继承实现),而Kotlin 类和函数都是默认 final 的,这样咱们须要为每一个类和函数前面加上open修饰符。这样的代码写起来很费事。还好,咱们有all-open 编译器插件。它会适配 Kotlin 以知足这些框架的需求,并使用指定的注解标注类而其成员无需显式使用 open 关键字打开。 例如,当咱们使用 Spring 时,就不须要打开全部的类,跟咱们在Java中写代码同样,只须要用相应的注解标注便可,如 @Configuration 或 @Service。
讲白了,引入这两个特定的插件的目的就是为了方便咱们向写SpringBt代码同样来写Kotlin程序!
这里面主要是跟Mysql数据库相关的一些配置:
spring.datasource.url = jdbc:mysql://localhost:3306/easykotlin
spring.datasource.username = root
spring.datasource.password = 你的Mysql密码
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.database = MYSQL
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = update
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
server.port=7000
复制代码
咱们须要去数据库中查询东西,因此二话不说,写个访问数据库的标准代码层:
各部分代码以下:
@Entity
class People(
@Id @GeneratedValue(strategy = GenerationType.AUTO)
val id: Long?,
val firstName: String?,
val lastName: String?,
val gender: String?,
val age: Int?,
val gmtCreated: Date,
val gmtModified: Date
) {
override fun toString(): String {
return "People(id=$id, firstName='$firstName', lastName='$lastName', gender='$gender', age=$age, gmtCreated=$gmtCreated, gmtModified=$gmtModified)"
}
}
复制代码
interface PeopleRepository : CrudRepository<People, Long> {
fun findByLastName(lastName: String): List<People>?
}
复制代码
@Service
class PeopleService : PeopleRepository {
@Autowired
val peopleRepository: PeopleRepository? = null
override fun findByLastName(lastName: String): List<People>? {
return peopleRepository?.findByLastName(lastName)
}
override fun <S : People?> save(entity: S): S? {
return peopleRepository?.save(entity)
}
override fun <S : People?> save(entities: MutableIterable<S>?): MutableIterable<S>? {
return peopleRepository?.save(entities)
}
override fun delete(entities: MutableIterable<People>?) {
}
override fun delete(entity: People?) {
}
override fun delete(id: Long?) {
}
override fun findAll(ids: MutableIterable<Long>?): MutableIterable<People>? {
return peopleRepository?.findAll(ids)
}
override fun findAll(): MutableIterable<People>? {
return peopleRepository?.findAll()
}
override fun exists(id: Long?): Boolean {
return peopleRepository?.exists(id)!!
}
override fun count(): Long {
return peopleRepository?.count()!!
}
override fun findOne(id: Long?): People? {
return peopleRepository?.findOne(id)
}
override fun deleteAll() {
}
}
复制代码
@Controller
class PeopleController {
@Autowired
val peopleService: PeopleService? = null
@GetMapping(value = "/hello")
@ResponseBody
fun hello(@RequestParam(value = "lastName") lastName: String): Any {
val peoples = peopleService?.findByLastName(lastName)
val map = HashMap<Any, Any>()
map.put("hello", peoples!!)
return map
}
}
复制代码
可见有了无参、全开放组件加持后,写代码和写Java的代码基本没区别了
首先须要去Mysql中建好数据库,并插入一些数据:
而后启动工程,访问: http://localhost:7000/hello?lastName=wang
能够看到数据成功被取回:
《Kotlin极简教程》
做者更多的SpringBt实践文章在此:
若是有兴趣,也能够抽点时间看看做者一些关于容器化、微服务化方面的文章: