2012-01-06 68 views
9

如何以编程方式获取项目的Maven版本?以编程方式获取项目的Maven版本

换句话说:

static public String getVersion() 
{ 
    ...what goes here?... 
} 

例如,如果我的项目将产生的jar CalculatorApp-1.2.3.jar,我想getVersion()返回1.2.3

+1

你的意思是在一个插件,或在应用程序本身? – 2012-01-06 21:09:48

+0

你打算如何使用maven版本?如果需要在构建过程中将信息包含在某个文件中,则可以使用[build-helper-maven-plugin](http://mojo.codehaus.org/build-helper-maven-plugin/maven -version-mojo.html),它会给你的Maven版本。 – CoolBeans 2012-01-06 21:11:37

+0

我可能误解了你的问题。如果你想获得你的项目的版本(不是像我之前的评论那样的maven版本),那么请看一看[这里](http://blog.nigelsim.org/2011/08/31/programmatically-getting-the -maven版本 - 的 - 你的项目/)。 – CoolBeans 2012-01-06 21:13:02

回答

16

src/main/resources使用以下内容创建文件version.prop

version=${project.version} 

以下内容添加到你项目的POM:

<build> 
... 
    <resources> 
     <resource> 
      <directory>src/main/resources</directory> 
      <filtering>true</filtering> 
      <includes> 
       <include>**/version.prop</include> 
      </includes> 
     </resource> 
     <resource> 
      <directory>src/main/resources</directory> 
      <filtering>false</filtering> 
      <excludes> 
       <exclude>**/version.prop</exclude> 
      </excludes> 
     </resource> 
    </resources> 
... 
</build> 

添加以下方法:

public String getVersion() 
{ 
    String path = "/version.prop"; 
    InputStream stream = getClass().class.getResourceAsStream(path); 
    if (stream == null) 
     return "UNKNOWN"; 
    Properties props = new Properties(); 
    try { 
     props.load(stream); 
     stream.close(); 
     return (String) props.get("version"); 
    } catch (IOException e) { 
     return "UNKNOWN"; 
    } 
} 

附:在这里找到这个解决方案的大部分:http://blog.nigelsim.org/2011/08/31/programmatically-getting-the-maven-version-of-your-project/#comment-124

+0

为什么第二个资源定义的过滤设置为false? – demaniak 2015-05-29 13:08:58

+0

@demaniak第一个副本只是version.properties并对其进行过滤,第二个副本只是version.properties的副本,并且不进行过滤。 – pauli 2015-12-04 14:31:21

相关问题