04.Kotlin与Gradle
04.Kotlin与Gradle
Kotlin 之 Gradle 基础
gradle project 和 task
用 kotlin 自定义 task
gradle 依赖
gradle 生命周期
- 扫描
- 执行
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
task("opendoor", {
println("open door scan1") // 扫描阶段
doFirst({
println("open door first") // 运行阶段
})
println("open door scan2") // 扫描阶段
doLast({
println("open door last") // 运行阶段
})
})
task("putelephant", {
println("put elephant scan")
doFirst({
println("put elephant first")
})
doLast({
println("put elephant last")
})
}).dependsOn("opendoor")
task("closedoor", {
println("close door scan")
doFirst({
println("close door first")
})
doLast({
println("close door last")
})
}).dependsOn("putelephant")
Tasks 任务集
多个任务的合集就是任务集
1
2
3
4
tasks { // 定义一堆任务
"xxx"{
}
}
gradle 默认 tasks,用命令 gradle tasks
查看默认 task
defaultTasks,定义 gradle 不输入 task 执行的默认 task
Gradle 增量更新
1
2
3
4
inputs.dir
inputs.file
outputs.dir
outputs.file
案例:把源代码的文件路径记录下来
1
2
3
4
5
6
7
8
9
10
11
12
13
task("getsrcname", {
var outputfile = file("ouput.txt")
doLast {
var srcDir = fileTree("src")
srcDir.forEach({
if (it.isFile) {
Thread.sleep(1000)
outputfile.appendText(it.absolutePath)
outputfile.appendText("\r\n")
}
})
}
})
未加入增量更新,如果没有变化,每次运行都需要 3s,加入只需要 0s,没有变化的 task 会是 UP-TO-DATE
状态
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
task("getsrcname", {
var outputfile = file("ouput.txt")
inputs.dir("src")
outputs.file(outputfile)
doLast {
var srcDir = fileTree("src")
srcDir.forEach({
if (it.isFile) {
Thread.sleep(1000)
outputfile.appendText(it.absolutePath)
outputfile.appendText("\r\n")
}
})
}
})
Gradle 常见插件
插件就是包含一个或多个 task 的合集
- application
- java
- war
Kotlin 之 Gradle DSL
https://github.com/gradle/kotlin-dsl
https://blog.gradle.org/kotlin-meets-gradle
build.gradle 转 build.gradle.kts
settings.gradle
include
1
2
3
4
5
6
include ':lancet-base'
project(':lancet-base').projectDir = File('lancet/lancet-base')
include ':lancet-weaver'
project(':lancet-weaver').projectDir = File('lancet/lancet-weaver')
include ':lancet-plugin'
project(':lancet-plugin').projectDir = File('lancet/lancet-plugin')
kotlin script:
1
2
3
4
5
6
include(":lancet-base")
project(":lancet-base").projectDir = File("lancet/lancet-base")
include(":lancet-weaver")
project(":lancet-weaver").projectDir = File("lancet/lancet-weaver")
include(":lancet-plugin")
project(":lancet-plugin").projectDir = File("lancet/lancet-plugin")
resolutionStrategy.dependencySubstitution substitute
- groovy
1
2
3
4
5
6
configurations.all {
resolutionStrategy.dependencySubstitution {
substitute module("org.utils:api") using project(":api") because "we work with the unreleased development version"
substitute module("org.utils:util:2.5") using project(":util")
}
}
- kts
1
2
3
4
5
6
7
configurations.all {
resolutionStrategy.dependencySubstitution {
substitute(module("org.utils:api"))
.using(project(":api")).because("we work with the unreleased development version")
substitute(module("org.utils:util:2.5")).using(project(":util"))
}
}
本文由作者按照 CC BY 4.0 进行授权