如何配置Gradle自定义插件使runMe任务随build任务自动执行?
runMe Task Auto-Execute with build Task Globally Got it, we can fix this by baking the task dependency directly into your custom Gradle plugin—no more repeating build.dependsOn runMe in every project that uses the plugin. Here's how to do it:
Step 1: Update Your Plugin's Core Logic
In your plugin's main implementation class (whether you're using Groovy or Kotlin DSL), you'll configure the build task to depend on runMe automatically whenever the plugin is applied.
Groovy Plugin Implementation
import org.gradle.api.Plugin import org.gradle.api.Project class MyPlugin implements Plugin<Project> { void apply(Project project) { // Register your runMe task (if you haven't already set it up) def runMeTask = project.tasks.register('runMe') { doLast { println "Executing custom runMe task!" // Add your task's actual logic here } } // Link the build task to depend on runMe project.tasks.named('build') { buildTask -> buildTask.dependsOn runMeTask } } }
Kotlin DSL Plugin Implementation
import org.gradle.api.Plugin import org.gradle.api.Project class MyPlugin : Plugin<Project> { override fun apply(project: Project) { // Register the runMe task val runMeTask = project.tasks.register("runMe") { doLast { println("Executing custom runMe task!") // Add your task's actual logic here } } // Make build task depend on runMe project.tasks.named("build") { dependsOn(runMeTask) } } }
Step 2: Optional Safety Check for Edge Cases
If you're working with projects that might not have a build task (uncommon for standard Java/Android/Groovy projects, but possible for specialized setups), add a safety check to avoid errors:
// For Groovy project.tasks.whenTaskAdded { task -> if (task.name == 'build') { task.dependsOn runMeTask } } // For Kotlin project.tasks.whenTaskAdded { task -> if (task.name == "build") { task.dependsOn(runMeTask) } }
How It Works
After updating your plugin and publishing a new version (e.g., 1.0.1), any project that applies id 'my.plugin.gradle-plugin' version '1.0.1' will automatically have the build task trigger runMe—no extra configuration needed in the project's build.gradle files.
内容的提问来源于stack exchange,提问作者F. Vorontsov

