maven打包在MANIFEST.MF檔案中增加屬性
阿新 • • 發佈:2019-01-01
最近在學習java agent,需要在生成的jar包裡面的 META-INF/MAINIFEST.MF 必須包含 Premain-Class這個屬性。採用MAVEN的maven-jar-plugin外掛完成。
maven-jar-plugin外掛預設生成的MAINIFEST.MF檔案包含以下幾項:
Manifest-Version: 1.0
Archiver-Version: Plexus Archiver
Created-By: Apache Maven
Built-By: ${user.name}
Build-Jdk: ${java.version}
現在要新增一個Premain-Class屬性,配置如下:
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <version>2.3.1</version> <configuration> <archive> <manifest> <addClasspath>true</addClasspath> </manifest> <manifestEntries> <Premain-Class> com.xzq.test.PreAgent </Premain-Class> </manifestEntries> </archive> </configuration> </plugin>
為什麼是在manifestEntries配置,通過檢視原始碼org.apache.maven.archiver.MavenArchiver,這個類在maven-archiver.jar中
addManifestAttribute方法原始碼如下:private void addCustomEntries(Manifest m, Map entries, ManifestConfiguration config) throws ManifestException { addManifestAttribute(m, entries, "Built-By", System.getProperty("user.name"));//設定變數<span style="color:#FF0000;">${user.name}</span> addManifestAttribute(m, entries, "Build-Jdk", System.getProperty("java.version"));//設定變數<span style="color:#FF0000;">${java.version}</span> if (config.getPackageName() != null) { addManifestAttribute(m, entries, "Package", config.getPackageName()); } }
private void addManifestAttribute(Manifest manifest, Map map, String key, String value)
throws ManifestException
{
if (map.containsKey(key))
{
return;
}
addManifestAttribute(manifest, key, value);
}
private void addManifestAttribute(Manifest manifest, String key, String value)
throws ManifestException
{
if (!StringUtils.isEmpty(value))
{ <span style="color:#FF0000;">//構造自定義屬性</span>
Manifest.Attribute attr = new Manifest.Attribute(key, value);
manifest.addConfiguredAttribute(attr);
}
else
{
Manifest.Attribute attr = new Manifest.Attribute(key, "");
manifest.addConfiguredAttribute(attr);
}
}