Spring Boot MVC应用读取META/MANIFEST.MF文件问题求助
外部Tomcat部署下读取Spring Boot应用自身MANIFEST.MF的解决方案
问题根源
用类加载器读取META-INF/MANIFEST.MF时,会从类路径中匹配第一个找到的文件(比如Tomcat依赖的commons-daemon.jar的),而非应用War包自身的MANIFEST.MF,导致无法获取自定义属性。
可行实现方案
方案一:通过ServletContext精准定位应用根目录的MANIFEST.MF
利用外部Tomcat部署时的Servlet上下文,直接获取应用War包根目录下的MANIFEST.MF:
@Configuration public class AppConfig { @Bean("manifest") public Manifest getManifest(ServletContext servletContext) throws IOException { URL manifestUrl = servletContext.getResource("/META-INF/MANIFEST.MF"); if (manifestUrl == null) { throw new IOException("未找到应用自身的MANIFEST.MF文件"); } try (InputStream inputStream = manifestUrl.openStream()) { return new Manifest(inputStream); } } }
方案二:通过当前类的代码源定位MANIFEST.MF
基于当前配置类的代码源,定位到应用自身的类路径或War包位置,再读取MANIFEST.MF:
@Configuration public class AppConfig { @Bean("manifest") public Manifest getManifest() throws IOException { ProtectionDomain domain = this.getClass().getProtectionDomain(); CodeSource codeSource = domain.getCodeSource(); if (codeSource == null) { throw new IOException("无法获取当前类的代码源信息"); } URL location = codeSource.getLocation(); URL manifestUrl = new URL(location, "META-INF/MANIFEST.MF"); try (InputStream inputStream = manifestUrl.openStream()) { return new Manifest(inputStream); } } }
补充:Gradle打包时确保自定义属性写入MANIFEST.MF
先在build.gradle中配置War打包时的Manifest属性,保证属性被正确写入:
war { manifest { attributes( 'Build-Number': project.version, // 可替换为构建变量,如System.getenv("BUILD_NUMBER") 'customPropInfo': '你的自定义属性值' ) } }
验证步骤
- 部署后检查Tomcat
webapps/你的应用名/META-INF/MANIFEST.MF,确认包含目标属性 - 在业务类中打印所有Manifest属性,验证读取的是应用自身文件:
@PostConstruct public void init() { Attributes mainAttributes = manifest.getMainAttributes(); mainAttributes.forEach((key, value) -> logger.info("{}: {}", key, value)); // 后续业务逻辑处理 }
内容的提问来源于stack exchange,提问作者Ravi
相关产品推荐
相关产品推荐

