如何以程序方式获取我的项目的Maven版本?
换一种说法:
static public String getVersion() { ...what goes here?... }
例如,如果我的项目会生成CalculatorApp-1.2.3.jar的jar,我希望getVersion()返回1.2.3.
解决方法
在src / main / resources中创建文件version.prop,内容如下:
version=${project.version}
<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