如何优雅地修改多模块maven项目中的版本号?

当我们用maven建立一个项目时,包含了多个子model,我们想把一个子model打包deploy到私服上去,需要:

1.从父节点把整个project都deploy上去,这时别人才能拉去到你上传的model。

2.保证整个project中所有model的version是一致的。

对于version,我们可以使用-SNAPSHOT这种方式,这样所有model都是一致的,每次发布也不会有问题。但如果项目发展比较快,需要使用release版本发布,由于release版本每次deploy时版本号不能重复,所以就需要每次都修改父model的version和子model的parent中的version。这时,就会有以下问题需思考:

  • 正式版不能重复发布,所以版本号每次上线都要更改
  • 当项目中包含几个子模块时,通常我们想让子模块的版本号跟父项目的版本号一致
  • 子模块也会相互依赖

最容易解决的是问题3,maven有一个内置属性${project.version}表示的是项目的版本号,当一个子模块依赖其他子模块时我们可以这样写:

<parent>
		<groupId>parent-groupId</groupId>
		<artifactId>parent-artifactId</artifactId>
		<version>1.0.0</version>
		<relativePath>..</relativePath>
	</parent>
	<artifactId>module-artifactId</artifactId>
	<dependency>
		<artifactId>other-module-artifactId</artifactId>
		<groupId>other-module-groupId</groupId>
		<version>${project.version}</version>
	</dependency>

子POM的groupId和version可以省略,这样只要保证子模块的版本号都一致就不会有问题了。但是<parent>标签中的版本号还是要写,不然会报错,显然maven没有进化到这么智能的程度,或者可能会造成其他混乱而必须指定。而投机取巧地把<parent>标签中的版本号换成${project.version}也没有成功,因为必须先初始化<parent>标签才能知道${project.version}是多少。

但是maven除了内置属性之外还可以自定义属性,我们可以在父pom中这样写:

<groupId>parent-groupId</groupId>
	<artifactId>parent-artifactId</artifactId>
	<version>${parent-version}</version>

	<properties>
		<parent-version>1.0.0</parent-version>
	</properties>

在子pom中这样写:

<parent>
	<groupId>parent-groupId</groupId>
	<artifactId>parent-artifactId</artifactId>
	<version>${parent-version}</version>
	<relativePath>..</relativePath>
</parent>

这样写达到了只修改一处的目的,但是在mvn install时会提示 <parent> 标签中的version不是一个常量,未来的版本可能不支持,而且各个子模块单独mvn install时可能会失败。

最终比较折中的解决方案是使用了maven的插件来解决,在父pom中这样写:

<groupId>parent-groupId</groupId>
	<artifactId>parent-artifactId</artifactId>
	<version>1.0.0</version>
	<build>
	<plugins>
		<plugin>
			<groupId>org.codehaus.mojo</groupId>
			<artifactId>versions-maven-plugin</artifactId>
			<version>2.3</version>
			<configuration>
				<generateBackupPoms>false</generateBackupPoms>
			</configuration>
		</plugin>
	</plugins>
	</build>

只需要执行mvn -N versions:update-child-modules则会自动把子POM的<parent>标签中的version更新为和父POM一致。这样修改一处然后运行一下执行一下命令就可以达到统一修改版本号的目的了。(在父model上执行后,所有子model中parent中的version都会修改)

猜你喜欢

转载自blog.csdn.net/liuxiao723846/article/details/81540919