使用 Maven 内置的版本号(Version)统一控制功能

从Maven 3.5 -beta-1开始 支持内置的 ${revision} (${sha1} and/or ${changelist}的使用方法,请查看Maven 文档[1])占位符作为 标签的值,用来控制整个项目的版本号。

<project>
	<groupId>xxx</groupId>
	<artifactId>xxx</artifactId>
	<version>${revision}</version>
</project>

可以通过执行 mvn 命令设置版本号:mvn -Drevision=1.0.0-SNAPSHOT clean package

也可以通过添加属性的形式设置版本号, 可以直接调用mvn clean package

<properties>
	<revision>2.0.0-SNAPSHOT</revision>
</properties>

该功能很好的支持了多模块应用的版本号统一(注意子模块之间依赖[1:1]以及插件的使用[2]):

<!-- parent.pom -->
<project>
	<groupId>group</groupId>
	<artifactId>parent</artifactId>
	<version>${revision}</version>

	<properties>
		<!-- 全局均可使用的变量 -->
		<revision>2.0.0-SNAPSHOT</revision> 
	</properties>
	
	<modules>
		<module>child-module</module>
	</modules>
	
	<dependencyManagement>
		<dependencies>
			  <dependency>
				<groupId>group</groupId>
				<artifactId>child-module</artifactId>
				<!-- 用于统一管理子模块之间的依赖,如需子模块自行管理依赖版本号,请参考 [1] Dependencies -->
				<version>${revision}</version>
			</dependency>
		</dependencies>
	</dependencyManagement>
	
	<!--对于 Install / Depoly 操作,必须使用该插件,否则无法将这个项目作为依赖添加 -->
	<build>
		<plugins>
			<plugin>
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>flatten-maven-plugin</artifactId>
				<version>1.7.3</version>
				<configuration>
					<updatePomFile>true</updatePomFile>
					<flattenMode>resolveCiFriendliesOnly</flattenMode>
				</configuration>
				<executions>
					<execution>
						<id>flatten</id>
						<phase>process-resources</phase>
						<goals>
							<goal>flatten</goal>
						</goals>
					</execution>
					<execution>
						<id>flatten.clean</id>
						<phase>clean</phase>
						<goals>
							<goal>clean</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>
</project>
<!-- child-module.pom -->
<project>
	<parent>
		<groupId>group</groupId>
		<artifactId>parent</artifactId>
		<version>${revision}</version>
	</parent>
	
	 <artifactId>child-module</artifactId>

</project>

  • 当使用插件后,会自动生成 .flattened-pom.xml 以代替原本的 pom.xml ,需要在 .gitignore文件中设置忽略:**/.flattened-pom.xml

参考:


  1. https://maven.apache.org/guides/mini/guide-maven-ci-friendly.html "Maven CI Friendly Versions" ↩︎ ↩︎

  2. https://github.com/mojohaus/flatten-maven-plugin "MojoHaus Flatten Maven Plugin" ↩︎

posted @ 2025-11-13 23:42  听风讲故事~  阅读(9)  评论(0)    收藏  举报