Java – get the Maven version of the project programmatically

How do I programmatically get the Maven version of my project?

To put it another way:

static public String getVersion()
{
    ...what goes here?...
}

For example, if my project generates calculatorapp-1.2 3. Jar, I want GetVersion () to return 1.2 three

Solution

Create the file version. In Src / main / resources Prop, as follows:

version=${project.version}

Add the following to the project's 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>

Add the following methods:

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";
    }
}

Attachment: find most solutions here: http://blog.nigelsim.org/2011/08/31/programmatically-getting-the-maven-version-of-your-project/#comment -124

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>