在大型项目中,需要统一规划依赖组件的版本,在Maven项目中通常通过BOM(Bill Of Materials)来实现。
备注:BOM全称是Bill Of Materials,译作材料清单。BOM本身并不是一种特殊的文件格式,而是一个普通的POM文件,只是在这个POM中,我们罗列的是一个工程的所有依赖和其对应的版本。该文件一般被其它工程使用,当其它工程引用BOM中罗列的jar包时,不用显示指定具体的版本,会自动使用BOM对应的jar版本。
<dependencyManagement> <dependencies> <dependency> <groupId>com.jianzh5</groupId> <artifactId>dailymart-dependencies</artifactId> <version>${revision}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <dependencies> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> </dependency> </dependencies>公共组件升级
<properties> <revision>2024.0.0-SNAPSHOT</revision> </properties>2、定义组件时直接使用revision变量作为版本号
<parent> <groupId>com.jianzh5</groupId> <artifactId>dailymart-boot</artifactId> <version>${revision}</version> </parent> <artifactId>dailymart-starter</artifactId>3、在bom文件中通过revision占位符引入公共组件
<dependencyManagement> <dependencies> <!-- Internal dependencies Start--> <dependency> <groupId>com.jianzh5</groupId> <artifactId>dailymart-common-spring-boot-starter</artifactId> <version>${revision}</version> </dependency> <dependency> <groupId>com.jianzh5</groupId> <artifactId>dailymart-ddd-spring-boot-starter</artifactId> <version>${revision}</version> </dependency> </dependencies> </dependencyManagement>这样,若公共组件需要修改版本,只需修改 revision 变量的值,各组件版本就会统一变更,非常方便。不过使用这种方式在公共组件模块执行 maven install 或 maven deploy 时会出现问题,推送到maven仓库中的pom文件仍然使用 revision 变量,业务模块无法直接引用。
<build> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>flatten-maven-plugin</artifactId> <version>${maven-flatten.version}</version> <configuration> <updatePomFile>true</updatePomFile> <flattenMode>resolveCiFriendliesOnly</flattenMode> </configuration> <executions> <execution> <id>flatten</id> <goals> <goal>flatten</goal> </goals> <phase>process-resources</phase> </execution> <execution> <id>flatten.clean</id> <goals> <goal>clean</goal> </goals> <phase>clean</phase> </execution> </executions> </plugin> </plugins> </build>在pom文件添加此插件后,执行 install 时会生成一个名为 .flattened-pom.xml 的文件,打开文件后可以看到 revision 变量已经全部替换成了具体的版本号。