如何在Gradle中从父项目获取依赖项版本

时间:2020-06-15 09:08:55

标签: spring gradle

我有一个Gradle项目,我想创建一个子模块,但是在构建项目时遇到了失败。

错误消息是

Execution failed for task ':child-project:compileJava'
> Could not resolve all files for configuration 'child-project:compileClasspath'.
  > Could not find org.springframework.boot:spring-boot-starter:.
    Required by:
        project :parent-project

这是父项目的build.gradle文件:

plugins {
  id 'org.springframework.boot' version '2.3.0.RELEASE'
  id 'io.spring.dependency-management' version '1.0.9.RELEASE'
  id 'java'
}

allprojects {
  apply plugin: 'java'
  group = 'com.test'

  sourceCompatibility = JavaVersion.VERSION_11
  targetCompatibility = JavaVersion.VERSION_11

  repositories {
    //local nexus
  }
}

dependencies {
  implementation 'org.springframework.boot:spring-boot-starter'
  implementation 'org.springframework.boot:spring-boot-starter-actuator'
  implementation 'org.springframework.boot:spring-boot-starter-web'
  //other dependencies
}

这是子项目build.gradle:

plugins {
  id 'java'
}

group = 'com.test'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = JavaVersion.VERSION_11

dependencies {
  compile 'org.springframework.boot:spring-boot-starter'

  testImplementation('org.springframework.boot:spring-boot-starter-test') {
    exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
  }
}

请帮助,谢谢。

1 个答案:

答案 0 :(得分:2)

为了能够指定不带版本的Spring Boot依赖项,您需要将Spring Boot插件应用于所有模块。现在,您仅在父项目中拥有它,而在子项目中则没有。

由于默认情况下应用插件也会禁用普通的jar任务,因此可以创建bootJar,因此您需要为库进行更改:

// Child build file
plugins {
    // Note that there are no versions on the plugins in the child project as this is defined by the ones in the parent
    id 'org.springframework.boot'
    id 'io.spring.dependency-management'
}

bootJar {
  enabled = false
}

jar {
  enabled = true
}

dependencies {
  implementation 'org.springframework.boot:spring-boot-starter'
}

或者,您也可以报废io.spring.dependency-management插件(和子项目中的org.springframework.boot插件),而是将Spring Boot BOM作为平台导入:

// Child build file (alternative)
dependencies {
  // Use 'platform' for making the versions in the BOM a recommendation only, and 'enforcedPlatform' for making them a requirement.
  // Note that you need the version of the BOM, so I recommend putting it in a property.
  implementation enforcedPlatform("org.springframework.boot:spring-boot-dependencies:2.3.0.RELEASE")

  // Here you can leave out the version
  implementation 'org.springframework.boot:spring-boot-starter'
}

我通常选择后者,因为这使我可以使用正常的Gradle语义。但这主要只是偏好。

(这只是构建脚本的小注释:不建议使用compile配置。它在compile 'org.springframework.boot:spring-boot-starter'行中使用。您可能只是从某处复制/粘贴了它,但是您应该替换它implementation。)