You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring打包JAR后无法找到log4j2-spring.xml配置文件求解

解决Log4J配置文件打包后找不到的问题

问题原因

IDE运行时,src/main/resources属于类路径的一部分,程序能直接读取到配置文件;但Maven打包后,该目录下的文件会被复制到JAR的类路径根目录(Spring Boot JAR则在BOOT-INF/classes/下),此时程序仍以src/main/resources/log4j2-spring.xml作为路径查找,自然找不到对应文件。

解决方案

1. 确保Maven正确打包资源文件

默认情况下Maven会自动将src/main/resources下的文件纳入JAR,但如果pom.xml有自定义build配置,需确认资源规则正确:

<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*.xml</include>
                <include>**/*.properties</include>
            </includes>
            <filtering>false</filtering>
        </resource>
    </resources>
</build>

这段配置确保所有xml、properties资源文件被正确打包到类路径。

2. 修改配置文件的引用方式

不要使用相对路径src/main/resources/log4j2-spring.xml,改用类路径前缀classpath::

  • 如果是通过JVM启动参数指定:
    将-Dlog4j.configurationFile=src/main/resources/log4j2-spring.xml改为-Dlog4j.configurationFile=classpath:log4j2-spring.xml
  • 如果是代码中指定:
    替换路径字符串为classpath:log4j2-spring.xml(注意Spring Boot项目无需额外指定,框架会自动扫描类路径下的log4j2-spring.xml)

3. 验证打包结果

执行命令查看JAR内的文件结构,确认配置文件存在:

jar tf your-application.jar

正常情况下,你会看到log4j2-spring.xml(或在BOOT-INF/classes/目录下)。

内容的提问来源于stack exchange,提问作者Erik Vasilyan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 20:12:03