Gradle 插件 DSL:声明位置限制

Gradle plugins DSL: Restriction on declaration location

我有几个 Gradle 脚本是通过 apply from: 'my-build.gradle' 应用的。如果我在外部构建文件 my-build.gradle 中使用新的插件 DSL,它会失败并出现以下错误:

> startup failed:
  Only Project build scripts can contain plugins {} blocks
  See http://gradle.org/docs/2.3/userguide/plugins.html#sec:plugins_block 
  for information on the plugins {} block

查看错误消息中指出的文档并没有揭示限制的原因。为什么对插件声明的位置有限制?

以下文件供参考。

  1. my-build.gradle 文件:

    plugins {
        id "net.saliman.cobertura" version "2.2.5"
    }
    
  2. build.gradle 文件:

    apply from: "my-build.gradle"
    
    // Other stuff
    

这就是您如何在外部 Gradle 文件中使用插件,例如您的 my-build.gradle:

buildscript {
  repositories {
    mavenCentral()
    maven { url "https://plugins.gradle.org/m2/" }
  }
  dependencies {
    classpath "org.sonarqube.gradle:gradle-sonarqube-plugin:1.1"
    classpath "net.saliman:gradle-cobertura-plugin:2.2.8"
  }
}
// Because this is a helper script that's sourced in from a build.gradle, we can't use the ID of external plugins
// We either use the full class name of the plugin without quotes or an init script: http://www.gradle.org/docs/current/userguide/init_scripts.html
apply plugin: org.sonarqube.gradle.SonarQubePlugin
apply plugin: net.saliman.gradle.plugin.cobertura.CoberturaPlugin

// rest of my-build.gradle omitted

上面我已经激活了SonarQube and Cobertura的插件。

通常,要获得插件的完全限定 class 名称,您必须查看其 .jar 文件。

至于技术原因为什么你不能在外部文件中使用plugins {}块,我不知道。它可能必须与 following:

做一些事情

[...] plugins [need to] be specified in a way that Gradle can easily and quickly extract [them], before executing the rest of the build script. It also requires that the definition of plugins to use be somewhat static.

但是rejoice:

Future versions of Gradle will remove this restriction.

我最近也遇到了类似的问题,通过更改 Intellij 中的 Gradle 设置解决了这个问题,如下所示: