关键词:spring-boot 依赖管理、spring-boot-dependencies、spring-boot-parent
问题
maven 工程,依赖管理是非常基本又非常重要的功能,现在的工程越来越庞大,依赖越来越多,各种二方包、三方包太多太多,依赖冲突处理起来真是让人头疼,经常需要涉及到多个地方需要调整。
微信公众号:逸飞兮(专注于java知识领域的源码分析,从源码中理解框架/工具原理、验证CS专业知识)
解决方案
使用统一的依赖管理模块来管理工程中的所有依赖。
spring-boot 工程常使用 spring-boot-dependencies、spring-boot-starter-parent 管理工程依赖。
spring-boot 的最上级工程是 spring-boot-build,以下开始一步一步深入了解 spring-boot 依赖解决方案。
spring-boot 中的方案
spring-boot-build
spring-boot 的最上层工程,指定了 maven profiles、maven repositories、maven pluginRepositories、maven build pluginManagement。
- profiles:中包含代码风格检查、代码风格 format;更方便导入 eclipse;maven 仓库
- repositories:允许在开发过程中导入快照和里程碑 BOM。这个部分在 install/deploy 期间被 flatten 插件删除。包含 maven 中央仓库、spring 快照仓库、spring 里程碑仓库
- pluginRepositories:插件仓库,包含 maven 中央仓库、spring 快照仓库、spring 里程碑仓库
- pluginManagement:构建插件管理,这个插件的配置只用于存储 Eclipse m2e 设置,它对 Maven 构建本身没有影响。
spring-boot-dependencies
dependencies 的父工程是spring-boot-build,不包含代码,只用 pom 来管理依赖,pom.xml 如下:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-build</artifactId>
<version>${revision}</version>
<relativePath>../..</relativePath>
</parent>
<artifactId>spring-boot-dependencies</artifactId>
<packaging>pom</packaging>
<dependencyManagement>
<!-- 省略具体依赖管理 -->
</dependencyManagement>
<build>
<pluginManagement>
<!-- 省略具体构建插件管理 -->
</pluginManagement>
<plugins>
<!-- 省略具体构建插件 -->
</plugins>
</build>
从 pom 中可以看出,spring-boot-dependencies 中除了引入了(3 个)插件,更多的是做版本的管理。
其中,引入的插件是:
- flatten-maven-plugin:对 pom 精简插件
- xml-maven-plugin:1. 根据 schema 验证 XML 文件;2. 使用 XSLT 样式转换 XML 文件
- build-helper-maven-plugin:指定多个源码目录
dependencyManagement 中差不多管理了 spring-boot 工程中所有的依赖。
pluginManagement 中管理了常用的各种 maven 插件,这里就不详述了。
其中包含了 maven-clean-plugin、maven-compiler-plugin、maven-assembly-plugin、maven-war-plugin、maven-jar-plugin、spring-boot-maven-plugin,其中 spring-boot-maven-plugin 插件对于 spring-boot 工程非常重要,会把 maven 打包成的 jar 重新打包成可执行 jar。
spring-boot-starter-parent(重要)
既然有了 spring-boot-dependencies 这么丰富的依赖、插件版本管理,那么还搞一个 spring-boot-starter-parent 呢?
spring-boot-starter-parent 的父工程是spring-boot-dependencies,不包含代码,只用 pom 来管理依赖,pom.xml 如下:
<parent>
<groupId>org.springframework.boot