问题

我注意到在Maven工件的JAR中,project.version属性包含在两个文件中:

META-INF/maven/${groupId}/${artifactId}/pom.properties
META-INF/maven/${groupId}/${artifactId}/pom.xml

是否有推荐的方法在运行时读取此版本?


#1 热门回答(226 赞)

你不需要访问特定于Maven的文件来获取任何给定库/类的版本信息。

你可以简单地使用getClass().getPackage().getImplementationVersion()来获取存储在.jar-filesMANIFEST.MF中的版本信息。幸运的是,Maven足够聪明,但默认情况下,Maven也没有向清单写入正确的信息!

相反,必须将maven-jar-plugin的414145828配置元素修改为setaddDefaultImplementationEntriesaddDefaultSpecificationEntriestotrue,如下所示:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jar-plugin</artifactId>
    <configuration>
        <archive>                   
            <manifest>
                <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
                <addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
            </manifest>
        </archive>
    </configuration>
</plugin>

理想情况下,此配置应该放入companypom或另一个基础。

有关<archive>元素的详细文档,请参见Maven Archive documentation


#2 热门回答(65 赞)

为了跟进上面的答案,对于a.warartifact,我发现我必须将等效配置应用到444149585,而不是31414670:

<plugin>
    <artifactId>maven-war-plugin</artifactId>
    <version>2.1</version>
    <configuration>
        <archive>                   
            <manifest>
                <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
                <addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
            </manifest>
        </archive>
    </configuration>
</plugin>

这在项目的.jar(包含在.warWEB-INF/lib中)中添加了版本信息到MANIFEST.MF


#3 热门回答(22 赞)

这是从pom.properties获取版本的方法,后退到从清单中获取它

public synchronized String getVersion() {
    String version = null;

    // try to load from maven properties first
    try {
        Properties p = new Properties();
        InputStream is = getClass().getResourceAsStream("/META-INF/maven/com.my.group/my-artefact/pom.properties");
        if (is != null) {
            p.load(is);
            version = p.getProperty("version", "");
        }
    } catch (Exception e) {
        // ignore
    }

    // fallback to using Java API
    if (version == null) {
        Package aPackage = getClass().getPackage();
        if (aPackage != null) {
            version = aPackage.getImplementationVersion();
            if (version == null) {
                version = aPackage.getSpecificationVersion();
            }
        }
    }

    if (version == null) {
        // we could not compute the version so use a blank
        version = "";
    }

    return version;
}

原文链接