gradle 中的多模块项目编译失败

Multi module project in gradle fails compile when

我正在使用 gradle 5.1.1 & 在我的多模块项目中有以下配置

settings.gradle

rootProject.name = 'multi-module-test'

include 'mock-api', 'mock-impl'

build.gradle

group 'com.acme'
version '1.0.0-SNAPSHOT'

subprojects {
  apply plugin: 'java'
  sourceCompatibility = 1.8

  repositories {
    mavenCentral()
  }
}

project(':mock-impl') {
  dependencies {
    // this fails
    // api project(':mock-api')

    // this succeeds
    implementation project(':mock-api')
  }
}

由于某些奇怪的原因,如果我使用 api 配置,构建会因这个原因而失败

Could not find method api() for arguments [project ':mock-api'] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.

但是当我使用implementation配置时它并没有失败

知道为什么会这样吗?

您遇到这个问题是因为您没有使用 java-library 插件。看看 gradle 文档,它说;

The key difference between the standard Java plugin and the Java Library plugin is that the latter introduces the concept of an API exposed to consumers.

所以尝试包括在内;

 plugins {
    id 'java-library'
}

参考: https://docs.gradle.org/5.1.1/userguide/java_library_plugin.html#header