加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 以编程方式获取项目的Maven版本

发布时间:2020-12-14 05:14:54 所属栏目:Java 来源:网络整理
导读:如何以程序方式获取我的项目的Maven版本? 换一种说法: static public String getVersion(){ ...what goes here?...} 例如,如果我的项目会生成CalculatorApp-1.2.3.jar的jar,我希望getVersion()返回1.2.3. 解决方法 在src / main / resources中创建文件vers
如何以程序方式获取我的项目的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}

将以下内容添加到项目的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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读