首页 > 解决方案 > Gradle 应用插件与插件

问题描述

我有一个简单的插件, greet任务是打印一些“Hello World”。

plugins {
    id 'java-gradle-plugin'
    id 'groovy'
    id 'maven-publish'
}

group = 'standalone.plugin2.greeting'
version = '1.0'

gradlePlugin {
    plugins {
        greeting {
            id = 'standalone.plugin2.greeting'
            implementationClass = 'standalone.plugin2.StandalonePlugin2Plugin'    
        }
    }
}

publishing {
    publications {
        maven(MavenPublication) {
            groupId = 'standalone.plugin2.greeting'
            version = '1.0'
            from components.java
        }
    }
}

现在,我有运行应用程序来运行greet task

buildscript {
    repositories {
        mavenLocal()
    }
    dependencies {
        classpath 'standalone.plugin2.greeting:standalone-plugin2:1.0'
    }
}

apply plugin: 'standalone.plugin2.greeting'

使用apply pluginnatation 可以正常工作,但是当我使用插件表示法时,如下所示:

plugins {
    id 'standalone.plugin2.greeting' version '1.0'
}

它不起作用。

错误信息是:

* What went wrong:
Plugin [id: 'standalone.plugin2.greeting', version: '1.0'] was not found in any of the following sources:

- Gradle Core Plugins (plugin is not in 'org.gradle' namespace)
- Plugin Repositories (could not resolve plugin artifact 'standalone.plugin2.greeting:standalone.plugin2.greeting.gradle.plugin:1.0')
  Searched in the following repositories:
    Gradle Central Plugin Repository

有什么区别?根据文档apply plugin是旧的,不应该使用。

标签: gradlegradle-plugin

解决方案


在引入plugins块之前,插件依赖项必须以与常规项目依赖项相同的方式使用 和 的组合来repositories解决dependencies。由于它们需要在运行实际构建脚本之前解决,因此需要在特殊buildscript块中定义它们:

buildscript {
    repositories {
        // define repositories for build script dependencies
    }
    dependencies {
        // define build script dependencies (a.k.a. plugins)
    }
}

repositories {
    // define repositories for regular project dependencies
}

dependencies {
    // define regular project dependencies
}

一旦解决了依赖关系,就可以使用apply plugin:.

默认情况下,新plugins块仅解析来自Gradle Plugin Repository的插件。这是一个常规的 Maven 存储库,因此也可以使用旧的方式使用它:

buildscript {
    repositories {
        maven {
            url "https://plugins.gradle.org/m2/"
        }
    }
}

在您的情况下,该插件仅存在于 中mavenLocal,因此该plugins块无法解析它,因为它仅查看 Gradle Central Plugin Repository。您可以使用该pluginManagement块来解析自定义存储库中的插件

如上面链接的文章中所述,有必要在插件标识符(在plugins块内使用)和提供相应插件的 Maven 坐标之间创建链接。要创建此链接,必须发布遵循特定约定的标记工件。如果与Maven Publish Plugin结合使用,Gradle Plugin Development Plugin会自动发布此标记工件。


推荐阅读