如何以编程方式获取项目的Maven版本?以编程方式获取项目的Maven版本
换句话说:
static public String getVersion()
{
...what goes here?...
}
例如,如果我的项目将产生的jar CalculatorApp-1.2.3.jar
,我想getVersion()
返回1.2.3
。
如何以编程方式获取项目的Maven版本?以编程方式获取项目的Maven版本
换句话说:
static public String getVersion()
{
...what goes here?...
}
例如,如果我的项目将产生的jar CalculatorApp-1.2.3.jar
,我想getVersion()
返回1.2.3
。
在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
你的意思是在一个插件,或在应用程序本身? – 2012-01-06 21:09:48
你打算如何使用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
我可能误解了你的问题。如果你想获得你的项目的版本(不是像我之前的评论那样的maven版本),那么请看一看[这里](http://blog.nigelsim.org/2011/08/31/programmatically-getting-the -maven版本 - 的 - 你的项目/)。 – CoolBeans 2012-01-06 21:13:02