[英]How to read war-file manifest in its jar-dependency?
How do I read the war
-file manifest property in its jar
-dependency?如何读取
jar
依赖项中的war
文件清单属性?
UPD: servlets are not used here (it's spring-bean initialization code). UPD:此处不使用 servlet(它是 spring-bean 初始化代码)。
Since a .war file's purpose is to handle servlets, I assume all of your code is called from servlets, or from a technology built on servlets, like JSP, JSF, or even Spring.由于 .war 文件的目的是处理 servlet,因此我假设您的所有代码都是从 servlet 调用的,或者是从构建在 servlet 上的技术(如 JSP、JSF 甚至 Spring)调用的。
Call the current request's getServletContext() method , and use the getResource or getResourceAsStream method of ServletContext.调用当前请求的getServletContext()方法,使用ServletContext的getResource或getResourceAsStream方法。 Those methods work just like the same methods of java.lang.Class, only they look in the .war file itself before searching the web application's classpath for a matching path.
这些方法的工作方式与 java.lang.Class 的方法相同,只是它们在搜索 Web 应用程序的类路径以查找匹配路径之前先查看 .war 文件本身。
For example:例如:
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));
}
}
Update:更新:
Since you want to read the manifest when preparing a Spring bean, it appears you can autowire a ServletContext object :由于您想在准备 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.