[英]How to read war-file manifest in its jar-dependency?
如何讀取jar
依賴項中的war
文件清單屬性?
UPD:此處不使用 servlet(它是 spring-bean 初始化代碼)。
由於 .war 文件的目的是處理 servlet,因此我假設您的所有代碼都是從 servlet 調用的,或者是從構建在 servlet 上的技術(如 JSP、JSF 甚至 Spring)調用的。
調用當前請求的getServletContext()方法,使用ServletContext的getResource或getResourceAsStream方法。 這些方法的工作方式與 java.lang.Class 的方法相同,只是它們在搜索 Web 應用程序的類路徑以查找匹配路徑之前先查看 .war 文件本身。
例如:
public Optional<Manifest> getWarManifest(ServletRequest request)
throws IOException {
InputStream manifest =
request.getServletContext().getResourceAsStream(
"/META-INF/MANIFEST.MF");
if (manifest == null) {
return Optional.empty();
}
try (InputStream stream = new BufferedInputStream(manifest)) {
return Optional.of(new Manifest(stream));
}
}
更新:
由於您想在准備 Spring bean 時讀取清單,看來您可以自動裝配 ServletContext 對象:
@Configuration
public class MyAppConfig {
@Bean
public MyBean createMyBean(@Autowired ServletContext context)
throws IOException {
Optional<Manifest> manifest;
InputStream source =
context.getResourceAsStream("/META-INF/MANIFEST.MF");
if (source == null) {
manifest = Optional.empty();
} else {
try (InputStream stream = new BufferedInputStream(source)) {
manifest = Optional.of(new Manifest(stream));
}
}
return new MyBean(manifest);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.