我希望能夠在執行過程中發現插件的版本; 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