Skip to content

Commit 3c901b8

Browse files
System AdministratorSystem Administrator
authored andcommitted
Spring Boot实战合集
0 parents  commit 3c901b8

File tree

157 files changed

+8727
-0
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

157 files changed

+8727
-0
lines changed

README.md

Whitespace-only changes.

kotlin_with_springbt/README.md

Lines changed: 272 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,272 @@
1+
2+
# 《Kotlin + Spring Boot联合编程》
3+
4+
---
5+
6+
> **长按****扫描** 下面的 **小心心** 来订阅作者公众号 **CodeSheep**,获取更多 **务实、能看懂、可复现的** 原创文 ↓↓↓
7+
8+
![CodeSheep · 程序羊](https://user-gold-cdn.xitu.io/2018/8/9/1651c0ef66e4923f?w=270&h=270&f=png&s=102007)
9+
10+
---
11+
12+
---
13+
14+
## 概述
15+
16+
Kotlin是一门最近比较流行的静态类型编程语言,而且和Groovy、Scala一样同属Java系。Kotlin具有的很多静态语言特性诸如:类型判断、多范式、扩展函数、模式匹配等等让我无法只作为一个吃瓜群众了,所以稍微花了点时间了解了一下该语言。
17+
18+
本文主要介绍一下如何使用Kotlin结合SpringBt开发一个带有数据库交互的REST风格基本程序
19+
20+
>**注:** 本文原载于 [**My Personal Blog:**](http://www.codesheep.cn)[**CodeSheep · 程序羊**](http://www.codesheep.cn)
21+
22+
---
23+
24+
## 实验环境
25+
26+
- JDK不用说了,Kotlin毕竟是运行在JVM环境下的语言,所以JDK必须,我这里用的JDK1.8
27+
- 数据库:MySQL
28+
- 数据库访问组件:Spring data jpa
29+
- J2EE框架:SpringBt 1.5.2.RELEASE
30+
- 构建工具:Gradle
31+
32+
---
33+
34+
## 工程创建
35+
36+
没啥好说的,我这里创建的是基于Gradle的Kotlin工程:
37+
38+
![基于Gradle的Kotlin工程](http://upload-images.jianshu.io/upload_images/9824247-baac893f0e5a1191.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
39+
40+
创建完成后的基本工程样式和SpringBt的工程几乎没任何区别,给张图示意一下好了:
41+
42+
![工程基本样式](http://upload-images.jianshu.io/upload_images/9824247-3c96778d62f47999.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
43+
44+
好啦,接下来我们就来写代码完善这个工程即可
45+
46+
---
47+
48+
## 完善build.gradle配置
49+
50+
我们需要在build.gradle中引入SpringBt依赖,除此之外还要引入一些特定的插件方便我们向写Java代码一样来写Kotlin程序!
51+
52+
在dependencies中加入如下依赖:
53+
```
54+
dependencies {
55+
compile "org.jetbrains.kotlin:kotlin-stdlib-jre8:$kotlin_version"
56+
testCompile group: 'junit', name: 'junit', version: '4.12'
57+
compile("org.springframework.boot:spring-boot-starter-web")
58+
testCompile("org.springframework.boot:spring-boot-starter-test")
59+
compile("org.springframework.boot:spring-boot-starter-data-jpa")
60+
compile('mysql:mysql-connector-java:5.1.13')
61+
}
62+
```
63+
64+
这样SpringBt相关的依赖就配置上了!
65+
66+
接下来我们配置两个非常关键的插件依赖:
67+
- 无参(no-arg)插件
68+
- 全开放(allopen)插件
69+
70+
我们先配上,等下解释:
71+
```
72+
buildscript {
73+
ext.kotlin_version = '1.1.1'
74+
ext.springboot_version = '1.5.2.RELEASE'
75+
76+
repositories {
77+
mavenCentral()
78+
}
79+
dependencies {
80+
// Kotlin Gradle插件
81+
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
82+
// SpringBoot Gradle插件
83+
classpath("org.springframework.boot:spring-boot-gradle-plugin:$springboot_version")
84+
// Kotlin整合SpringBoot的默认无参构造函数,默认把所有的类设置open类插件
85+
classpath("org.jetbrains.kotlin:kotlin-noarg:$kotlin_version") // 无参插件
86+
classpath("org.jetbrains.kotlin:kotlin-allopen:$kotlin_version") // 全开放插件
87+
}
88+
}
89+
```
90+
91+
其中(以下解释源自《Kotlin极简教程》):
92+
- org.jetbrains.kotlin:kotlin-noarg是无参(no-arg)编译器插件,它为具有特定注解的类生成一个额外的零参数构造函数。 这个生成的构造函数是合成的,因此不能从 Java 或 Kotlin 中直接调用,但可以使用反射调用。 这样我们就可以使用 Java Persistence API(JPA)实例化 data 类。
93+
94+
- org.jetbrains.kotlin:kotlin-allopen 是全开放编译器插件。我们使用Kotlin 调用Java的Spring AOP框架和库,需要类为 open(可被继承实现),而Kotlin 类和函数都是默认 final 的,这样我们需要为每个类和函数前面加上open修饰符。这样的代码写起来很费事。还好,我们有all-open 编译器插件。它会适配 Kotlin 以满足这些框架的需求,并使用指定的注解标注类而其成员无需显式使用 open 关键字打开。 例如,当我们使用 Spring 时,就不需要打开所有的类,跟我们在Java中写代码一样,只需要用相应的注解标注即可,如 @Configuration@Service
95+
96+
97+
讲白了,引入这两个特定的插件的目的就是为了方便我们向写SpringBt代码一样来写Kotlin程序!
98+
99+
---
100+
101+
## 配置application.properties
102+
103+
这里面主要是跟Mysql数据库相关的一些配置:
104+
105+
```
106+
spring.datasource.url = jdbc:mysql://localhost:3306/easykotlin
107+
spring.datasource.username = root
108+
spring.datasource.password = 你的Mysql密码
109+
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
110+
spring.jpa.database = MYSQL
111+
spring.datasource.testWhileIdle = true
112+
spring.datasource.validationQuery = SELECT 1
113+
spring.jpa.show-sql = true
114+
spring.jpa.hibernate.ddl-auto = update
115+
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
116+
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
117+
118+
server.port=7000
119+
```
120+
121+
---
122+
123+
## 正式编写工程
124+
125+
我们需要去数据库中查询东西,所以二话不说,写个访问数据库的标准代码层:
126+
- controller
127+
- entity
128+
- repository
129+
- service
130+
131+
![整体代码框架](http://upload-images.jianshu.io/upload_images/9824247-e8cd8481ead01eeb.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
132+
133+
各部分代码如下:
134+
135+
- People.kt
136+
137+
```
138+
@Entity
139+
class People(
140+
@Id @GeneratedValue(strategy = GenerationType.AUTO)
141+
val id: Long?,
142+
val firstName: String?,
143+
val lastName: String?,
144+
val gender: String?,
145+
val age: Int?,
146+
val gmtCreated: Date,
147+
val gmtModified: Date
148+
) {
149+
override fun toString(): String {
150+
return "People(id=$id, firstName='$firstName', lastName='$lastName', gender='$gender', age=$age, gmtCreated=$gmtCreated, gmtModified=$gmtModified)"
151+
}
152+
}
153+
```
154+
155+
- PeopleRepository.kt
156+
157+
```
158+
interface PeopleRepository : CrudRepository<People, Long> {
159+
fun findByLastName(lastName: String): List<People>?
160+
}
161+
```
162+
163+
- PeopleService.kt
164+
165+
```
166+
@Service
167+
class PeopleService : PeopleRepository {
168+
169+
@Autowired
170+
val peopleRepository: PeopleRepository? = null
171+
172+
override fun findByLastName(lastName: String): List<People>? {
173+
return peopleRepository?.findByLastName(lastName)
174+
}
175+
176+
override fun <S : People?> save(entity: S): S? {
177+
return peopleRepository?.save(entity)
178+
}
179+
180+
override fun <S : People?> save(entities: MutableIterable<S>?): MutableIterable<S>? {
181+
return peopleRepository?.save(entities)
182+
}
183+
184+
override fun delete(entities: MutableIterable<People>?) {
185+
}
186+
187+
override fun delete(entity: People?) {
188+
}
189+
190+
override fun delete(id: Long?) {
191+
}
192+
193+
override fun findAll(ids: MutableIterable<Long>?): MutableIterable<People>? {
194+
return peopleRepository?.findAll(ids)
195+
}
196+
197+
override fun findAll(): MutableIterable<People>? {
198+
return peopleRepository?.findAll()
199+
}
200+
201+
override fun exists(id: Long?): Boolean {
202+
return peopleRepository?.exists(id)!!
203+
}
204+
205+
override fun count(): Long {
206+
return peopleRepository?.count()!!
207+
}
208+
209+
override fun findOne(id: Long?): People? {
210+
return peopleRepository?.findOne(id)
211+
}
212+
213+
override fun deleteAll() {
214+
}
215+
}
216+
```
217+
218+
- PeopleController.kt
219+
220+
```
221+
@Controller
222+
class PeopleController {
223+
@Autowired
224+
val peopleService: PeopleService? = null
225+
226+
@GetMapping(value = "/hello")
227+
@ResponseBody
228+
fun hello(@RequestParam(value = "lastName") lastName: String): Any {
229+
val peoples = peopleService?.findByLastName(lastName)
230+
val map = HashMap<Any, Any>()
231+
map.put("hello", peoples!!)
232+
return map
233+
}
234+
}
235+
```
236+
237+
可见有了无参、全开放组件加持后,写代码和写Java的代码基本没区别了
238+
239+
---
240+
241+
## 实际实验
242+
243+
首先需要去Mysql中建好数据库,并插入一些数据:
244+
245+
![数据库预览](http://upload-images.jianshu.io/upload_images/9824247-1f59d8e3ae409028.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
246+
247+
然后启动工程,访问:
248+
http://localhost:7000/hello?lastName=wang
249+
250+
可以看到数据成功被取回:
251+
252+
![成功获取到数据](http://upload-images.jianshu.io/upload_images/9824247-6bc738ccd94b1e88.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
253+
254+
---
255+
256+
## 参考文献
257+
258+
《Kotlin极简教程》
259+
260+
---
261+
262+
## 后记
263+
264+
> 由于能力有限,若有错误或者不当之处,还请大家批评指正,一起学习交流!
265+
266+
- [My Personal Blog](http://www.codesheep.cn/)
267+
- [我的半年技术博客之路](https://www.jianshu.com/p/28ba53821450)
268+
269+
---
270+
271+
272+
---

kotlin_with_springbt/build.gradle

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
group 'com.hansonwang99'
2+
version '1.0-SNAPSHOT'
3+
4+
buildscript {
5+
ext.kotlin_version = '1.1.1'
6+
ext.springboot_version = '1.5.2.RELEASE'
7+
8+
repositories {
9+
mavenCentral()
10+
}
11+
dependencies {
12+
// Kotlin Gradle插件
13+
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
14+
// SpringBoot Gradle插件
15+
classpath("org.springframework.boot:spring-boot-gradle-plugin:$springboot_version")
16+
// Kotlin整合SpringBoot的默认无参构造函数,默认把所有的类设置open类插件
17+
classpath("org.jetbrains.kotlin:kotlin-noarg:$kotlin_version")
18+
classpath("org.jetbrains.kotlin:kotlin-allopen:$kotlin_version")
19+
}
20+
}
21+
22+
apply plugin: 'java'
23+
apply plugin: 'kotlin'
24+
apply plugin: 'kotlin-spring'
25+
apply plugin: 'kotlin-jpa'
26+
apply plugin: 'org.springframework.boot'
27+
28+
sourceCompatibility = 1.8
29+
targetCompatibility = 1.8
30+
31+
repositories {
32+
mavenCentral()
33+
}
34+
35+
dependencies {
36+
compile "org.jetbrains.kotlin:kotlin-stdlib-jre8:$kotlin_version"
37+
testCompile group: 'junit', name: 'junit', version: '4.12'
38+
compile("org.springframework.boot:spring-boot-starter-web")
39+
testCompile("org.springframework.boot:spring-boot-starter-test")
40+
compile("org.springframework.boot:spring-boot-starter-data-jpa")
41+
compile('mysql:mysql-connector-java:5.1.13')
42+
}
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
rootProject.name = 'kotlin_with_springbt'
2+
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package com.hansonwang99.kotlin
2+
3+
import org.springframework.boot.SpringApplication
4+
import org.springframework.boot.autoconfigure.SpringBootApplication
5+
6+
/**
7+
* Created by Administrator on 2018/1/23.
8+
*/
9+
10+
@SpringBootApplication
11+
class Application
12+
13+
fun main(args: Array<String>) {
14+
SpringApplication.run(Application::class.java, *args)
15+
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package com.hansonwang99.kotlin.controller
2+
3+
import com.hansonwang99.kotlin.service.PeopleService
4+
import org.springframework.beans.factory.annotation.Autowired
5+
import org.springframework.stereotype.Controller
6+
import org.springframework.web.bind.annotation.GetMapping
7+
import org.springframework.web.bind.annotation.RequestParam
8+
import org.springframework.web.bind.annotation.ResponseBody
9+
10+
/**
11+
* Created by Administrator on 2018/1/23.
12+
*/
13+
@Controller
14+
class PeopleController {
15+
@Autowired
16+
val peopleService: PeopleService? = null
17+
18+
@GetMapping(value = "/hello")
19+
@ResponseBody
20+
fun hello(@RequestParam(value = "lastName") lastName: String): Any {
21+
val peoples = peopleService?.findByLastName(lastName)
22+
val map = HashMap<Any, Any>()
23+
map.put("hello", peoples!!)
24+
return map
25+
}
26+
27+
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package com.hansonwang99.kotlin.entity
2+
3+
import java.util.*
4+
import javax.persistence.Entity
5+
import javax.persistence.GeneratedValue
6+
import javax.persistence.GenerationType
7+
import javax.persistence.Id
8+
9+
/**
10+
* Created by Administrator on 2018/1/23.
11+
*/
12+
13+
@Entity
14+
class People(
15+
@Id @GeneratedValue(strategy = GenerationType.AUTO)
16+
val id: Long?,
17+
val firstName: String?,
18+
val lastName: String?,
19+
val gender: String?,
20+
val age: Int?,
21+
val gmtCreated: Date,
22+
val gmtModified: Date
23+
) {
24+
override fun toString(): String {
25+
return "People(id=$id, firstName='$firstName', lastName='$lastName', gender='$gender', age=$age, gmtCreated=$gmtCreated, gmtModified=$gmtModified)"
26+
}
27+
}

0 commit comments

Comments
 (0)