Maven插件如何在执行期间发现自己的版本?

时间:2010-07-01 19:10:42

标签: java maven-2 version maven-plugin

我希望能够在执行过程中发现插件的版本; 0.0.1-SNAPSHOT,0.0.1,1.0-SNAPSHOT等

可以这样做吗? AbstractMojo类并没有真正为您提供有关插件本身的更多信息。

编辑 - 我使用以下代码作为解决方法。它假定可以从使用插件本身的资源URL构建的资源URL加载插件的MANIFEST。它不是很好,但似乎适用于位于文件或jar类加载器中的MANIFEST:

String getPluginVersion() throws IOException {
    Manifest mf = loadManifest(getClass().getClassLoader(), getClass());
    return mf.getMainAttributes().getValue("Implementation-Version");
}

Manifest loadManifest(final ClassLoader cl, final Class c) throws IOException {
    String resourceName = "/" + c.getName().replaceAll("\\.", "/") + ".class";
    URL classResource = cl.getResource(resourceName);
    String path = classResource.toString();

    int idx = path.indexOf(resourceName);
    if (idx < 0) {
        return null;
    }

    String urlStr = classResource.toString().substring(0, idx) + "/META-INF/MANIFEST.MF";

    URL url = new URL(urlStr);

    InputStream in = null;
    Manifest mf = null;
    try {
        in = url.openStream();
        mf = new Manifest(in);
    } finally {
        if (null != in) {
            in.close();
        }
        in = null;
    }

    return mf;
}

2 个答案:

答案 0 :(得分:1)

我认为你对清单文件的“解决方法”并不是一个坏主意。因为它被打包在插件的.jar中,所以你应该始终可以访问它。

这篇文章是一个答案,这是另一个想法:让maven在你的插件构建期间为你做脏工作:在你的插件源中有一个占位符:

private final String myVersion = "[CURRENT-VERSION]";

在编译之前使用ant-plugin或其他东西用当前版本替换该占位符。

答案 1 :(得分:0)

首先,将以下依赖项添加到插件的POM中:

<dependency>
  <groupId>org.apache.maven</groupId>
  <artifactId>maven-project</artifactId>
  <version>2.0</version>
</dependency>

然后您可以执行以下操作:

public class MyMojo extends AbstractMojo {

private static final String GROUP_ID = "your-group-id";
private static final String ARTIFACT_ID = "your-artifact-id";

/**
 * @parameter default-value="${project}"
 */
MavenProject project;

public void execute() throws MojoExecutionException {
    Set pluginArtifacts = project.getPluginArtifacts();
    for (Iterator iterator = pluginArtifacts.iterator(); iterator.hasNext();) {
        Artifact artifact = (Artifact) iterator.next();
        String groupId = artifact.getGroupId();
        String artifactId = artifact.getArtifactId();
        if (groupId.equals(GROUP_ID) && artifactId.equals(ARTIFACT_ID)) {
            System.out.println(artifact.getVersion());
            break;
        }
    }
}
相关问题