Spring Boot和Kotlin的無縫整合與完美交融
前言
本文講解 Spring Boot2 基礎(chǔ)下,如何使用 Kotlin,并無縫整合與完美交融。為了讓讀者更加熟悉 Kotlin 的語法糖,筆者會在未來的幾篇文章中,聊聊 Kotlin 的新特性及其語法糖。下面話不多說了,來一起看看詳細(xì)的介紹吧
環(huán)境依賴
修改 POM 文件,添加 spring boot 依賴。
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.2.RELEASE</version> <relativePath/> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> </dependencies>
緊接著,我們需要添加 mysql 依賴。
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.35</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.14</version> </dependency>
最后,添加 Kotlin 依賴。
<dependency> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-stdlib-jdk8</artifactId> </dependency> <dependency> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-reflect</artifactId> </dependency> <dependency> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-stdlib</artifactId> </dependency>
注意的是,在 Kotlin 中,data class 默認(rèn)沒有無參構(gòu)造方法,并且 data class 默認(rèn)為 final 類型,不可以被繼承。注意的是,如果我們使用 Spring + Kotlin 的模式,那么使用 @autowared 就可能遇到這個問題。因此,我們可以添加 NoArg 為標(biāo)注的類生成無參構(gòu)造方法。使用 AllOpen 為被標(biāo)注的類去掉 final,允許被繼承。
<plugin>
<artifactId>kotlin-maven-plugin</artifactId>
<groupId>org.jetbrains.kotlin</groupId>
<version>${kotlin.version}</version>
<executions>
<execution>
<id>compile</id>
<goals> <goal>compile</goal> </goals>
</execution>
<execution>
<id>test-compile</id>
<goals> <goal>test-compile</goal> </goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-noarg</artifactId>
<version>${kotlin.version}</version>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-allopen</artifactId>
<version>${kotlin.version}</version>
</dependency>
</dependencies>
</plugin>
至此,我們 Maven 的依賴環(huán)境大致配置完畢。完整的源碼,可以參見文末 GitHub 倉庫。
數(shù)據(jù)源
方案一 使用 Spring Boot 默認(rèn)配置
使用 Spring Boot 默認(rèn)配置,不需要在創(chuàng)建 dataSource 和 jdbcTemplate 的 Bean。
在 src/main/resources/application.properties 中配置數(shù)據(jù)源信息。
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
方案二 手動創(chuàng)建
在 src/main/resources/config/source.properties 中配置數(shù)據(jù)源信息。
# mysql source.driverClassName = com.mysql.jdbc.Driver source.url = jdbc:mysql://localhost:3306/springboot_db source.username = root source.password = root
這里, 創(chuàng)建 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 操作
實(shí)體對象
class Author {
var id: Long? = null
var realName: String? = null
var nickName: String? = null
}
DAO相關(guān)
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<Author>
}
我們來定義實(shí)現(xiàn)類,通過 JdbcTemplate 定義的數(shù)據(jù)訪問操作。
@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<Author>("select * from t_author where id = ?",
arrayOf<Any>(id), BeanPropertyRowMapper(Author::class.java))
return list?.get(0);
}
override fun findAuthorList(): List<Author> {
return jdbcTemplate.query("select * from t_author", arrayOf(), BeanPropertyRowMapper(Author::class.java))
}
}
Service相關(guān)
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<Author>
}
我們來定義實(shí)現(xiàn)類,Service 層調(diào)用 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<Author> {
return this.authorDao.findAuthorList()
}
}
Controller相關(guān)
為了展現(xiàn)效果,我們先定義一組簡單的 RESTful API 接口進(jìn)行測試。
@RestController
@RequestMapping(value = "/authors")
class AuthorController {
@Autowired
private lateinit var authorService: AuthorService
/**
* 查詢用戶列表
*/
@RequestMapping(method = [RequestMethod.GET])
fun getAuthorList(request: HttpServletRequest): Map<String, Any> {
val authorList = this.authorService.findAuthorList()
val param = HashMap<String, Any>()
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("刪除錯誤")
}
}
}
最后,我們通過 SpringKotlinApplication 運(yùn)行程序。
@SpringBootApplication(scanBasePackages = ["com.lianggzone.demo.kotlin"])
open class SpringKotlinApplication{
fun main(args: Array<String>) {
SpringApplication.run(SpringKotlinApplication::class.java, *args)
}
}
關(guān)于測試
這里,筆者推薦 IDEA 的 Editor REST Client。IDEA 的 Editor REST Client 在 IntelliJ IDEA 2017.3 版本就開始支持,在 2018.1 版本添加了很多的特性。事實(shí)上,它是 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
總結(jié)
通過,上面這個簡單的案例,我們發(fā)現(xiàn) Spring Boot 整合 Kotlin 非常容易,并簡化 Spring 應(yīng)用的初始搭建以及開發(fā)過程。為了讓讀者更加熟悉 Kotlin 的語法糖,筆者會在未來的幾篇文章中,聊聊 Kotlin 的新特性及其語法糖。
源代碼
相關(guān)示例完整代碼: spring-kotlin-samples (本地下載)
好了,以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
相關(guān)文章
MybatisPlus字段類型轉(zhuǎn)換的實(shí)現(xiàn)示例
本文主要介紹了MybatisPlus如何完成字段類型轉(zhuǎn)換,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-03-03
Java通過httpclient比較重定向和請求轉(zhuǎn)發(fā)
這篇文章主要介紹了Java通過httpclient比較重定向和請求轉(zhuǎn)發(fā),HttpClient?4.x?版本,get請求方法會自動進(jìn)行重定向,而post請求方法不會自動進(jìn)行重定向,需要的朋友可以參考下2023-04-04
Java concurrency之LockSupport_動力節(jié)點(diǎn)Java學(xué)院整理
這篇文章主要為大家詳細(xì)介紹了Java concurrency之LockSupport的相關(guān)資料,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-06-06
spring和quartz整合,并簡單調(diào)用(實(shí)例講解)
下面小編就為大家?guī)硪黄猻pring和quartz整合,并簡單調(diào)用(實(shí)例講解)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-07-07
完整的醫(yī)院就診掛號系統(tǒng)基于Spring MVC + Spring + MyBatis實(shí)現(xiàn)
這篇文章主要介紹了基于Spring MVC + Spring + MyBatis實(shí)現(xiàn)的醫(yī)院就診掛號系統(tǒng),本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-08-08
SpringBoot之spring.factories的使用方式
這篇文章主要介紹了SpringBoot之spring.factories的使用方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-01-01
Java8中Lambda表達(dá)式使用和Stream API詳解
這篇文章主要給大家介紹了關(guān)于Java8中Lambda表達(dá)式使用和Stream API的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用Java8具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-05-05
Java實(shí)現(xiàn)自定義語言和表達(dá)式解析的解釋器模式
Java解釋器設(shè)計模式通過解析自定義語言和表達(dá)式,實(shí)現(xiàn)對復(fù)雜邏輯的處理,提高程序可擴(kuò)展性和靈活性。它將語法解析和執(zhí)行過程分離,通過抽象語法樹和解釋器實(shí)現(xiàn)對語言和表達(dá)式的解析和求值,避免了硬編碼和復(fù)雜的條件判斷,提高了程序的可讀性和可維護(hù)性2023-04-04

