天天看點

Maven多子產品實作統一版本管理

在使用Maven多子產品結構工程時,配置版本号是一個比較頭疼的事。繼承版本、依賴版本、自身版本都需要單獨定義,很是麻煩。比如在微服務系統中,所有服務都依賴一個包,裡面進行版本管理。每個服務的version版本管理卻是單獨使用一個版本号。然後我們在版本快速疊代中,通常是要不斷地切換version,當服務衆多的時候,修改起版本來就很麻煩。

Maven官方文檔說:自 Maven 3.5.0-beta-1 開始,可以使用 ${revision}, ${sha1} and/or ${changelist} 這樣的變量作為版本占位符。

指令

mvn clean install versions:set -DnewVersion=2.0.2      

 單子產品項目

<project>
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.xh</groupId>
  <artifactId>personal-platform</artifactId>
  <version>${project.build.version}</version>
  ...
  <properties>
      <project.build.version>2.0.3</project.build.version>
  </properties>

</project>      

這種情況比較簡單,隻使用了 ${project.build.version} 來替換版本。

多子產品項目

現在來看看多子產品建構的情況,有一個父項目和一個或多子子產品。

父pom

<project>
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.xh</groupId>
    <artifactId>personal-platform</artifactId>
    <packaging>pom</packaging>
    <version>${project.build.version}</version>

    ...
    <properties>
        <project.build.version>2.0.3</project.build.version>
    </properties>

    <modules>
        <module>commons-center</module>
    </modules>
</project>      

子pom

<project>
    <parent>
        <artifactId>personal-platform</artifactId>
        <groupId>com.anchnet</groupId>
        <version>${project.build.version}</version>
    </parent>

    <modelVersion>4.0.0</modelVersion>
    <artifactId>commons-center</artifactId>
    <packaging>pom</packaging>

</project>      

多子產品項目中子子產品的版本應該使用父工程的版本,單獨設定版本的話會導緻版本混亂。

打包

package、install、deploy

如果使用以上設定來釋出,必須使用 flatten-maven-plugin

<build>
    <plugins>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>flatten-maven-plugin</artifactId>
            <version>1.3.0</version>
            <configuration>
                <!--true:更新pom檔案,不然無法更新module裡的pom版本号,此處還有更進階的用法,具體參靠官方文檔-->
                <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>