我希望能够在执行过程中发现插件的版本; 0.0.1-SNAPSHOT,0.0.1,1.0-SNAPSHOT等。Maven插件在执行期间如何发现它自己的版本?
可以这样做吗? AbstractMojo类并没有给你提供关于插件本身的更多信息。
编辑 - 我正在使用下面的代码作为解决方法。它假定可以从使用插件本身的资源URL构建的资源URL加载插件的MANIFEST。这不是很好,但似乎对清单位于任一文件或jar类加载器的工作:
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;
}
我不认为这是正确的。如果插件是针对POM运行的,那么将返回POM的版本,而不是插件的版本。 – 2010-07-02 09:21:37
嗨保罗,是的,你是对的,它给了项目的版本,而不是插件。我相应地更新了代码。这不是一个非常优雅的解决方案,但似乎工作。也许别人知道一个更干净的方式来做到这一点。 – 2010-07-02 21:08:52