如何以编程方式获取项目的 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
关于java - 以编程方式获取项目的 Maven 版本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8764500/