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

标签 java 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

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

相关文章:

JAVA-日期间隔时间,错误的结果

java - Maven全新安装问题: Failed to configure plugin parameters

java - Java 后台作业管理器?

基于操作系统的 Maven antrun 插件设置属性

java - "This method is deprecated as the user should use the Java 5 conventions."这是什么意思?

java - 为什么 hadoop 不能识别我的 Map 类?

java - 仅在 Eclipse 中? java.lang.NoSuchMethodError : org. springframework.beans.factory.annotation.InjectionMetadata.needsRefresh

java - 缺少请求正文的 Spring Boot POST 请求?

grails maven集成

java - maven-dependency-plugin 不能排除测试范围依赖