自定義插件有三種方式
Build script
在 build.gradle 腳本中直接編寫插件。插件被包含在構(gòu)建腳本中华坦,會自動編譯间驮,簡單方便驾凶。但該插件不可再其他構(gòu)建腳本中使用尘奏,不具備可重用性滩褥。
class GreetingPlugin implements Plugin<Project> {
void apply(Project project) {
project.task('hello') {
doLast {
println 'Hello from the GreetingPlugin'
}
}
}
}
// Apply the plugin
apply plugin: GreetingPlugin
可以通過 project.extensions
讓插件具有可配置性
class GreetingPluginExtension {
String message
String greeter
}
class GreetingPlugin implements Plugin<Project> {
void apply(Project project) {
def extension = project.extensions.create('greeting', GreetingPluginExtension)
project.task('hello') {
doLast {
println "${extension.message} from ${extension.greeter}"
}
}
}
}
apply plugin: GreetingPlugin
// Configure the extension using a DSL block
greeting {
message = 'Hi'
greeter = 'Gradle'
}
buildSrc project
Standalone project
可以為插件單獨創(chuàng)建一個項目,發(fā)布成 JAR 供其他項目使用炫加。獨立項目中可以包含多個插件或多個相關(guān)的任務(wù)類瑰煎。
創(chuàng)建項目
IDEA -> New Module -> module name(wiki)
build.gradle
plugins {
id 'java'
id 'maven-publish'
}
group 'com.hooda'
version '1.0.0'
repositories {
mavenCentral()
}
dependencies {
implementation gradleApi()
testCompile group: 'junit', name: 'junit', version: '4.12'
}
publishing {
publications {
wiki(MavenPublication) {
groupId "com.hooda"
artifactId "wiki"
version "1.0.0"
from components.java
}
}
}
maven-publish 支持將插件發(fā)布到本地 maven 倉庫,方便后續(xù)的調(diào)試
java -> com.hooda.WikiPlugin
public class WikiPlugin implements Plugin<Project> {
@Override
public void apply(Project project) {
System.out.println("execute wiki plugin");
}
}
resources -> META-INF\gradle-plugins\wiki.properties
implementation-class=com.hooda.WikiPlugin
選擇 Gradle -> wiki(module) -> Tasks -> publishing -> publishWikiPublicationToMavenLocal 將插件發(fā)布到本地 Maven 倉庫俗孝,后續(xù)在其他模塊中就可以引入該插件應(yīng)用酒甸。
應(yīng)用插件
IDEA -> New Module -> module name(wikiapi)
build.gradle
buildscript {
repositories {
mavenLocal()
mavenCentral()
}
dependencies {
classpath "com.hooda:wiki:1.0.0"
}
}
group 'com.hooda'
version '1.0.0'
repositories {
mavenCentral()
}
apply plugin: 'java'
apply plugin: 'wiki'
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.12'
}
插件調(diào)試
開啟遠程調(diào)試:
Run -> Edit Configurations -> +(Add New Configuration) -> Remote
應(yīng)用遠程調(diào)試:
Gradle -> api(應(yīng)用模塊)-> Tasks -> build -> builld -> 右鍵 -> Create 'xx [build]
在 VM opitions 中添加,注意:suspend=y
-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=5005
將會在 Run Configurations 中新增一個 build赋铝,雙擊 就可以開始調(diào)試了