我想阅读我的WAR应用程序的MANIFEST.MF文件。我该如何找到它的文件名?
我怎么找到它的文件名?
你已经有了它。也许你想找到绝对文件位置?你可以使用ServletContext#getRealPath()
。
String relativeWARPath = "/META-INF/MANIFEST.MF";
String absoluteDiskPath = getServletContext().getRealPath(relativeWARPath);
File file = new File(absoluteDiskPath);
// ...
或者,如果您想直接将其作为InputStream
获取,请使用ServletContext#getResourceAsStream()
。
InputStream input = getServletContext().getResourceAsStream("/META-INF/MANIFEST.MF");
// ...
ServletContext
。看起来我需要在web.xml
中注册我的自定义ServletContextListener
。对吗? - yegor256ServletContextListener
怎么样?我走对了吗? - yegor256我在每个应用程序中都遇到了同样的问题,于是决定创建一个包含实用类的组件:jcabi-manifests。现在可以轻松地从类路径中任何可用的MANIFEST.MF
加载任何属性:
import com.jcabi.manifests.Manifests;
String value = Manifests.read("My-Version");
另外,看看这个:http://www.yegor256.com/2014/07/03/how-to-read-manifest-mf.html
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.2</version>
<configuration>
<archive>
<manifest>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
<addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
</manifest>
</archive>
</configuration>
</plugin>
@Override public void contextInitialized(ServletContextEvent servletContextEvent)
@Override public void contextInitialized(ServletContextEvent servletContextEvent) {
logger.info("context initialized - reading MANIFEST.MF infos");
StringBuilder welcomeStrBuild;
welcomeStrBuild = new StringBuilder("version");
try (InputStream inputStream = servletContextEvent.getServletContext().getResourceAsStream("/META-INF/MANIFEST.MF")) {
Properties prop = new Properties();
prop.load(inputStream);
welcomeStrBuild.append(prop.getProperty("Implementation-Version", "n/a"));
} catch (Exception e) {
logger.info("Unable to extract info from MANIFEST.MF");
welcomeStrBuild.append("Unable to extract info from MANIFEST.MF");
}
infoProject = welcomeStrBuild.toString();
servletContextEvent.getServletContext().setAttribute("config", this);
}
有几种方法可以做到这一点,而所选择的答案仅适用于您想要在Servlet/SpringMVC层或任何您可以访问ServletContext的层上读取Manifiest文件的情况。
但是,如果您想要在Servlet启动之前甚至在logback配置或其他某些情况下读取像"version"这样的值,您可能需要进行一些旧式类加载或Manifest文件操作。
我发现了这个Github库(不是我的),其中包括4种不同的方式从Manifest文件中读取信息。如果您的情况无法访问ServletContext,请查看这些内容。