方案1
在应用项目中,如果应用程序需要获取当前程序的版本号,可以读取”/META-INF/maven/${groupId}/${artifactId}/pom.properties“,获取maven生成的版本信息。
当然前提用应用程序在运行时得知道自己的groupId和artifactId,否则无法定位路径。
pom.properties内容示例
#Created by Apache Maven .5.0version=1.0.4-SNAPSHOT
groupId=com.gitee.l0km
artifactId=facelog-service
这种方法很简单,但也有缺点:
貌似这种方法只能获取maven默认定义${project.version},无法加入自定义的信息。
方案2
还有一个方案就是直接将版本信息写入MANIFEST.MF。通过java.util.jar.Manifest来读取解析MANIFEST.MF来获取版本号。
如下增加buildnumber-maven-plugin插件,并给maven-jar-plugin插件指定写入MANIFEST.MF的参数。
org.codehaus.mojo
buildnumber-maven-plugin
1.2
create
org.apache.maven.plugins
maven-jar-plugin
3.0.2
${project.version}
${buildNumber}
${maven.build.timestamp}
方案3
前面两种方案,都需要将应用程序打成jar包才能读取版本信息。
那么程序在开发调试的时候,并没有生成pom.properties,和MANIFEST.MF,也就无法读取版本信息了。
所以另一种思路就是用 template-maven-plugin插件让maven自动生成一个包含版本信息的代码如Version.java。这样任何时候,程序都能很方便的知道自己的版本号了。
模板
首先需要一个代码模板Version.java,示例如下:
packagenet.gdface.facelog.service;public final classVersion {/**project version*/
public static final String VERSION = "${project.version}";/**SCM(git) revision*/
public static final String SCM_REVISION= "${buildNumber}";/**SCM branch*/
public static final String SCM_BRANCH = "${scmBranch}";/**build timestamp*/
public static final String TIMESTAMP ="${buildtimestamp}";
}
模板放在/src/main/java/java-templates/${package_of_template}/下
原本在模板文件中用maven内置变量${maven.build.timestamp}做时间戳,实际运行并没有被正确替换,不知道原因。所以改为使用buildnumber-maven-plugin插件(goal create-timestamp)生成的时间戳${buildtimestamp}
插件
然后修改pom.xml增加 template-maven-plugin插件和buildnumber-maven-plugin插件
org.codehaus.mojo
buildnumber-maven-plugin
1.4
bn1
create
bn2
create-timestamp
buildtimestamp
yyyy-MM-dd HH:mm:ss
org.codehaus.mojo
templating-maven-plugin
1.0.0
filter-src
filter-sources
template-maven-plugin插件会将/src/main/java/java-templates/文件夹下的所有模板中的${xxx}占位符都用maven中同名的变量替换一遍,
生成的Version.java在${project.build.directory}/generated-sources/${package_of_template}下,并且该文件夹会自动成为源码文件夹加入编译过程。
参考资料
《Generate a Version.java file in Maven》