Maven 生成编译时间和版本Java类
本文使用Maven插件来自动生成一个 Version.java
类,可以在Java代码中使用里面对应的常量,获取当前版本号和构建时间。
Maven编译后自动生成的 Version.java
文件内容如下所示:
package com.shanhy.demo;public final class Version {public static String NUMBER = "0.0.41-SNAPSHOT";public static String BUILD_TIME = "2023-08-15 10:54:16";
}
pom.xml 中插件的使用示例如下所示:
<plugin><groupId>org.codehaus.mojo</groupId><artifactId>build-helper-maven-plugin</artifactId><version>3.4.0</version><executions><execution><id>timestamp-property</id><goals><goal>timestamp-property</goal></goals><configuration><name>current.time</name><pattern>yyyy-MM-dd HH:mm:ss</pattern><timeZone>GMT+8</timeZone><locale>zh_CN</locale></configuration></execution></executions>
</plugin>
<plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-antrun-plugin</artifactId><version>3.0.0</version><executions><execution><goals><goal>run</goal></goals><phase>generate-sources</phase><configuration><target><property name="src.dir" value="${project.build.sourceDirectory}"/><property name="package.dir" value="com/shanhy/demo"/><property name="package.name" value="com.shanhy.demo"/><!--maven.build.timestamp是UTC时间,跟北京时间有8个小时的时差,使用插件 build-helper-maven-plugin:timestamp-property 解决这个时差问题--><!--<property name="buildtime" value="${maven.build.timestamp}"/>--><property name="buildtime" value="${current.time}"/><!--生成一个 Version.java 文件,里面生成常量,可以在Java代码中直接使用--><echo file="${src.dir}/${package.dir}/Version.java"message="package ${package.name};${line.separator}${line.separator}"/><echo file="${src.dir}/${package.dir}/Version.java" append="true"message="public final class Version {${line.separator}"/><echo file="${src.dir}/${package.dir}/Version.java" append="true"message=" public static String NUMBER = "${project.version}";${line.separator}"/><echo file="${src.dir}/${package.dir}/Version.java" append="true"message=" public static String BUILD_TIME = "${buildtime}";${line.separator}"/><echo file="${src.dir}/${package.dir}/Version.java" append="true"message="}${line.separator}"/></target></configuration></execution></executions>
</plugin>
你也可用这种方法生成普通的版本配置文件,例如 version.properties,上文生成 java 文件是为了在 Java 代码中的相关业务中直接使用常量。
(END)