在pom.xml中自动增加版本号并在应用程序中显示它

我多次看到这个问题,但是没有令人满意的答案:让我们假设你有maven项目生产一些jar(java桌面应用程序)。 如何在pom.xml中定义版本号,在适当的时候(例如,每次构建时)会自动递增(甚至手动,无关紧要),但是可以将此版本加载到应用程序中? 目标是为用户显示他当前使用的应用程序的版本。

您可以选择四个选项:

  1. 使用Maven默认创建的pom.properties文件。
  2. 使用MANIFST.MF文件提供的信息。 有几种方法可以获取这些信息。
  3. 创建在构建过程中过滤的属性,并由应用程序读取。
  4. 使用包含适当信息的生成类。

第一个选项可以由Java类处理, 如下所示 :

public class TheVersionClass { .. public TheVersionClass() { InputStream resourceAsStream = this.getClass().getResourceAsStream( "/META-INF/maven/com.soebes.examples/version-examples-i/pom.properties" ); this.prop = new Properties(); try { this.prop.load( resourceAsStream ); } ... } } 

第二个选项是使用MANIFEST.MF文件

 public class TheVersionClass { public TheVersionClass() { System.out.println( " Implementation Title:" + this.getClass().getPackage().getImplementationTitle() ); System.out.println( " Implementation Vendor:" + this.getClass().getPackage().getImplementationVendor() ); System.out.println( "Implementation Version:" + this.getClass().getPackage().getImplementationVersion() ); System.out.println( " Specification Tile:" + this.getClass().getPackage().getSpecificationTitle() ); System.out.println( " Specification Vendor:" + this.getClass().getPackage().getSpecificationVendor() ); System.out.println( " Specification Version:" + this.getClass().getPackage().getSpecificationVersion() ); } } 

不幸的是,这些信息通常不会被放入MANIFEST.MF文件中,因此您必须更改配置。

第三个选项是创建一个在构建过程中作为资源被过滤的文件,第四个选项是使用templating-maven-plugin来创建适当的类。 以上所有内容都可以在github项目中查看。

当然,您可以使用buildnumber-maven-plugin将任何示例增强到使用buildnumber-maven-plugin将信息从版本控制系统添加到MANIFEST.MF文件中,方法是使用以下代码段,该代码段应位于模块的根目录中或更好地进入公司pom文件,添加它为每个构建执行:

   org.codehaus.mojo buildnumber-maven-plugin 1.2  UNKNOWN true  javasvn      create     

如果您只有一个新版本,我不会更改版本。 将Jenkins或您正在使用的任何CI解决方案的buildnumber添加到MANIFEST.MF文件中可能很有用,但我会使用Maven的版本,在发布的情况下将从1.0-SNAPSHOT更改为1.0