文章翻译自 www.baeldung.com
,已得到作者授权。
1.Introduction
在本教程中,我们将了解 spring-boot-starter-parent
以及我们如何从中受益,以实现更好的依赖关系管理,插件的默认配置以及快速构建 Spring Boot
应用程序。
我们还将看到如何覆盖 starter-parent
提供的现有依赖项和属性的版本。
2.Spring Boot Starter Parent
spring-boot-starter-parent
项目是一个特殊的 starter project
- 它为我们的应用程序提供了默认配置
,并提供了一个完整的依赖树
来快速构建我们的 Spring Boot
项目。
它还为Maven插件提供默认配置,例如 maven-failsafe-plugin
,maven-jar-plugin
,maven-surefire-plugin
,maven-war-plugin
。
除此之外,它还从 spring-boot-dependencies
继承了依赖关系管理,spring-boot-dependencies
是 spring-boot-starter-parent
的父级。
我们可以在项目的 pom.xml
中将其添加为父项,从而开始在项目中使用它:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.5.RELEASE</version>
</parent>
我们总是可以从 Maven Central
获得最新版本的 spring-boot-starter-parent
.
3.Managing Dependencies
一旦我们在项目中声明了 starter parent
,我们可以通过在 dependencies
标签中声明它,来从父项中提取任何依赖项。
此外,我们不需要定义依赖项的版本,Maven
将根据在父标记中为 starter parent
定义的版本下载 jar
文件。
例如,如果我们正在构建一个 Web
项目,我们可以直接添加 spring-boot-starter-web
,我们不需要指定版本:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
4.The Dependency Management Tag
要管理由 starter parent
提供的不同版本的依赖项,我们可以在 dependencyManagement
部分中显式声明依赖项及其版本:
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>2.1.1.RELEASE</version>
</dependency>
</dependencies>
</dependencyManagement>
5. Properties
要更改 starter parent
中定义的任何属性的值,我们可以在属性部分中重新声明它。
spring-boot-starter-parent
通过其父 spring-boot-dependencies
使用属性来配置所有依赖版本
,Java版本
和Maven插件版本
。
因此,只需更改相应的属性,即可轻松控制这些配置。
如果我们想要更改从 starter parent
中提取的任何依赖项的版本,我们可以在依赖项标记中添加依赖项并直接配置其属性:
<properties>
<junit.version>4.12</junit.version>
</properties>
6. Other Property Overrides
我们还可以将属性用于其他配置,例如管理插件版本,甚至是一些基本配置,例如管理Java版本,源代码编码。
我们只需要用新值重新声明属性。
例如,要更改Java版本,我们可以在java.version属性中指明它:
<properties>
<java.version>1.8</java.version>
</properties>
7. Spring Boot Project Without Starter Parent
有时我们有一个自定义的Maven父级。或者,我们可能更愿意手动声明所有Maven配置。
在这种情况下,我们可能选择不使用spring-boot-starter-parent项目。但是,通过在导入范围的项目中添加依赖spring-boot-dependencies,我们仍然可以从其依赖树中受益。
让我们用一个简单的例子来解释这个问题,在这个例子中我们想要使用除启动父级之外的另一个父级:
<parent>
<groupId>com.baeldung</groupId>
<artifactId>spring-boot-parent</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
在这里,我们使用父模块 将不同的项目作为父依赖项。
现在,在这种情况下,我们仍然可以通过在导入范围和 pom
类型中添加依赖项管理来获得相同的好处:
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.1.1.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
此外,我们可以通过在依赖项中声明它来引入任何依赖,就像我们在前面的示例中所做的那样。这些依赖项不需要版本号。
8. Summary
在本教程中,我们概述了 spring-boot-starter-parent
以及在任何子项目中将其添加为父项的好处。
之后,我们学习了如何管理依赖项。我们可以在dependencyManagement
中或通过属性覆盖依赖项。
Github上提供了本教程中使用的片段的源代码,其中一个使用了启动父级,另一个使用了自定义父级。