关于如何自定义Plugin,可以参考之前的自定义Plugin
1 创建extension
class TraceManPlugin implements Plugin<Project>{
final String TAG = getClass().getSimpleName() + ": "
@Override
void apply(Project project) {
println(TAG + "apply() enter")
//1 创建extension
project.extensions.create("testConfig", CustomExtension)
//2 使用extension
def config = project.testConfig
println(TAG + "config.path = " + config.path + ", openConfig = " + config.open)
project.gradle.afterProject {
println(TAG + "afterProject config.path = " + config.path + ", openConfig = " + config.open)
}
}
}
testConfig是extension的name, CustomExtension是extensino的类型
2 使用自定义的extension
testConfig {
path = "/release/com/text"
open = true
}
当执行./gradlew :app:assembleDebug时,就会输出config的值。
TraceManPlugin: apply() enter
TraceManPlugin: config.path = null, openConfig = false
TraceManPlugin: afterProject config.path = /release/com/text, openConfig = true
但是有个问题,直接在自定义Plugin的apply()方法中取出自定义extension的值,是空值,必须要在afterProject的闭包中才能取出来。
gradle的版本是6.5
------------------------------------------------------------
Gradle 6.5
------------------------------------------------------------
Build time: 2020-06-02 20:46:21 UTC
Revision: a27f41e4ae5e8a41ab9b19f8dd6d86d7b384dad4
Kotlin: 1.3.72
Groovy: 2.5.11
Ant: Apache Ant(TM) version 1.10.7 compiled on September 1 2019
JVM: 1.8.0_333 (Oracle Corporation 25.333-b02)
OS: Mac OS X 10.15.7 x86_64