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

时间:2014-02-19 17:42:36

标签: java maven build jar version

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

1 个答案:

答案 0 :(得分:3)

您可以选择四个选项:

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

    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 );
            }
            ...
        }
    }
    

    second option is to use the MANIFEST.MF file

    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文件中,因此您必须更改配置。

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

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

      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>buildnumber-maven-plugin</artifactId>
        <version>1.2</version>
        <configuration>
          <revisionOnScmFailure>UNKNOWN</revisionOnScmFailure>
          <getRevisionOnlyOnce>true</getRevisionOnlyOnce>
          <providerImplementations>
            <svn>javasvn</svn>
          </providerImplementations>
        </configuration>
        <executions>
          <execution>
            <goals>
              <goal>create</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    

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

相关问题