编写groovy插件
在使用build.gradle
编译项目时,需要使用
apply plugin: "xxxxx"
告诉build.gradle
接下来要编译的是什么项目类型,不同的项目类型规定有不同的文件目录,所以在创建项目时,一旦项目类型确定,该项目的文件目录结构也是确定的。
当指定的文件类型为gradle插件时,其文件目录树为:
- 建立模块根目录:在项目根目录下添加
script
文件夹- 为插件模块添加
build.gradle
: 在script
目录下建立build.gradle
文件,并指定将要编译的项目为groovy
插件//: build.gradle apply plugin: "groovy" dependencies { implementation gradleApi() implementation localGroovy() }
3.构建模块内容目录:在
script
目录下建立src/main
文件夹,并在src/main
文件目录下创建groovy
和resources
文件夹,并在groovy
和resources
文件夹中添加如上图的子文件a) 其中
MyPlugin.groovy
为插件的groovy
文件,代码如下:package com.example.script import org.gradle.api.Plugin import org.gradle.api.Project class MyPlugin implements Plugin<Project> { @Override void apply(Project project) { //定义任务名称为testPlugin project.task("testPlugin", { println("hello gradle plugin is src") }) } }
b) 注意
META-INF/gradle-plugins
下建立的properties
文件的文件名就是插件的名称
- 在配置文件中注册插件类:
implementation-class=com.example.script.MyPlugin
将插件上传至本地Maven仓库
在插件模块根目录的build.gradle
文件中添加将插件上传至本地maven
,最终的build.gradle
文件为
apply plugin: "groovy"
dependencies {
implementation gradleApi()
implementation localGroovy()
}
apply plugin: 'maven'
group = 'com.github.xxxxx'
version = '1.0.0'
uploadArchives {
repositories {
mavenDeployer {
//本地的Maven地址设置为../repos
repository(url: uri('../repo'))
}
}
}
然后,在gradle的任务栏中执行插件上传本地maven
仓库的Task
。
在项目中使用插件
在项目的build.gradle
中添加插件的本地maven
地址和classpath
buildscript {
repositories {
google()
jcenter()
maven {
url uri('./repo')
}
}
dependencies {
classpath 'com.github.jiarwang:script:1.0.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
在需要使用的模块的build.gradle
中使用插件,插件名称应与插件配置文件.properties
的文件名一致
apply plugin : 'com.plugin.gradle'
最后在Task
中执行相关任务。