You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置Gradle自定义插件使runMe任务随build任务自动执行?

How to Make Custom Plugin's 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:51:54