如何在 build.gradle 中的版本之间进行选择

how to choose between versions in build.gradle

如果您有一个包含行 implementation 'org.springframework.boot:spring-boot-starter-web' 的 build.gradle 文件,您如何选择它下载的 jar 版本以便获得最新版本?我看到一个项目是 2.2.4 版本,但在另一个项目中我看到了 2.2.5 版本的同一行。

一个可能的解决方案是使用锁定文件和 + 的一个版本,或者 major.minor.+major.+

的组合
 implementation 'org.springframework.boot:spring-boot-starter-web:+'

有关依赖锁定的更多信息:https://docs.gradle.org/current/userguide/dependency_locking.html

另一种方法,我对可用的方法非常满意,是使用物料清单,它通过引入约束来指定许多依赖项的版本。因此,在使用依赖项且未指定版本的情况下,如您的示例所示,它将获得 BOM 引入的版本。因此对于下面的依赖项,如果它存在于 BOM 中,它将匹配

implementation 'org.springframework.boot:spring-boot-starter-web

如果您愿意,您也可以通过仍然指定版本来手动覆盖版本。 BOM 与任何其他依赖项一样,因此您可以混合使用锁定文件和 BOM。

这里是 gradle 物料清单文档:https://docs.gradle.org/current/userguide/platforms.html

由于您删除了名称 Spring Boot,我假设项目已经生成 Spring Initializr。使用 Initializr 生成的项目应用了两个插件:

io.spring.dependency-management 是 Spring 为 Gradle 构建提供类似 Maven 的依赖管理的固执己见的方式。它允许声明依赖版本一次,然后在声明实际依赖时省略版本。

org.springframework.boot 插件执行以下操作:

When you apply the io.spring.dependency-management plugin, Spring Boot’s plugin will automatically import the spring-boot-dependencies bom from the version of Spring Boot that you are using. This provides a similar dependency management experience to the one that’s enjoyed by Maven users. For example, it allows you to omit version numbers when declaring dependencies that are managed in the bom. To make use of this functionality, simply declare dependencies in the usual way but omit the version number.

(From: Managing Dependencies)

这在实践中意味着什么?

当您为 Spring Boot 2.1.14 生成项目时,您的 build.gradle 将类似于:

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

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

org.springframework.boot 插件指示 io.spring.dependency-management 应用 Spring Boot 2.1.14 的物料清单 (BOM)。 BOM 为 spring-boot-starter-web 声明以下版本:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>2.1.14.RELEASE</version>
</dependency>

(来自:Maven Central

并且此组合允许在 build.gradle 中声明对 spring-boot-starter-web 的依赖,而无需提供实际版本:

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

如果您要更改 org.springframework.boot Gradle 插件的版本,则会应用与 Spring 引导版本相匹配的不同版本。

您可能会问,为什么要付出如此巨大的努力?

We take an opinionated view of the Spring platform and third-party libraries so you can get started with minimum fuss.

这就是原因。