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

Fat JAR中Log4J实现缺失异常排查求助

Log4J Fat JAR 运行异常排查方案

核心问题分析

命令行运行fat JAR时出现Log4J实现未找到的注入异常,本质是SPI服务加载机制失效——Log4J2通过META-INF/services下的配置文件定位实现类,打包过程中该文件被覆盖或缺失,导致JVM无法找到Log4J核心实现。

针对性解决方法

1. 修复Maven打包插件的SPI文件合并逻辑

如果使用maven-shade-plugin,必须添加ServicesResourceTransformer来合并所有依赖的SPI配置文件,避免被覆盖:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-shade-plugin</artifactId>
    <version>3.4.1</version>
    <executions>
        <execution>
            <phase>package</phase>
            <goals>
                <goal>shade</goal>
            </goals>
            <configuration>
                <transformers>
                    <!-- 合并所有META-INF/services下的配置文件 -->
                    <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
                    <!-- 自动生成MANIFEST.MF并指定主类 -->
                    <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                        <mainClass>你的主类全路径,比如com.example.Main</mainClass>
                    </transformer>
                </transformers>
            </configuration>
        </execution>
    </executions>
</plugin>

若使用maven-assembly-plugin,需手动配置文件合并规则,推荐优先使用shade插件,对SPI支持更完善

2. 确认依赖完整性

检查pom.xml中是否同时包含Log4J API和核心实现,且未设置scope为provided(会被排除在打包外):

<dependencies>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-api</artifactId>
        <version>2.20.0</version>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>2.20.0</version>
    </dependency>
</dependencies>

3. 避免手动编写MANIFEST.MF

手动编写的MANIFEST.MF容易出现类路径或主类配置错误,建议通过Maven插件自动生成,确保Main-Class和Class-Path配置正确。

验证步骤

  1. 解压fat JAR,检查META-INF/services/org.apache.logging.log4j.core.LoggerContextFactory文件,确认内容包含org.apache.logging.log4j.core.impl.Log4jContextFactory
  2. 检查JAR包内是否存在org/apache/logging/log4j/core/impl/Log4jContextFactory.class文件
  3. 运行时添加调试参数:java -Dlog4j.debug=true -jar example.jar,查看Log4J加载日志,定位具体缺失资源

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 20:52:45