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

Java Modules报错:org.slf4j模块未找到及后续问题求解

Java Modules与SLF4J依赖问题排查与解决

问题场景

我在学习Java Modules时遇到了两个关联问题:

  1. 最初模块声明如下:
module mymodule {
  requires org.slf4j;
} 

执行mvn clean package时触发报错:

Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.10.1:compile module not found: org.slf4j

我的pom.xml依赖配置为:

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

<dependency>
  <groupId>org.apache.logging.log4j</groupId>
  <artifactId>log4j-slf4j-impl</artifactId>
</dependency>
  1. 修改模块声明为自动模块名后:
module mymodule {
  requires org.apache.logging.log4j.slf4j;
}

又出现新错误:

(package org.slf4j is declared in the unnamed module, but module org.slf4j does not read it)

问题原因分析

第一个错误:module not found: org.slf4j

  • pom.xml中未直接引入SLF4J核心依赖包slf4j-api,仅引入了Log4J对SLF4J的实现包log4j-slf4j-impl。尽管log4j-slf4j-impl会间接依赖slf4j-api,但Java模块系统编译时需要明确找到对应模块的描述文件(module-info.class)。
  • 早期版本的slf4j-api可能是未模块化的JAR(无module-info.java),此时它会被视为未命名模块,无法通过requires org.slf4j直接引用——因为这个模块名不存在。

第二个错误:包在未命名模块中,模块无法读取

  • 改用requires org.apache.logging.log4j.slf4j后,这个自动模块确实存在,但代码直接引用了org.slf4j包下的类,而该包属于未命名模块的slf4j-api。
  • Java模块系统中,显式模块(你的mymodule)只能读取其他显式模块,或通过requires static/requires transitive声明的依赖,未命名模块的内容默认不会被显式模块读取,因此触发该错误。

解决步骤

1. 添加SLF4J核心依赖

在pom.xml中直接引入slf4j-api,确保版本与log4j-slf4j-impl兼容:

<dependency>
  <groupId>org.slf4j</groupId>
  <artifactId>slf4j-api</artifactId>
  <!-- 建议指定与log4j-slf4j-impl匹配的版本,比如2.x系列对应SLF4J 1.7.x或2.x -->
  <version>1.7.36</version>
</dependency>

2. 正确配置模块声明

从SLF4J 1.7.x开始,slf4j-api已支持自动模块,自动模块名为org.slf4j。模块声明可保持最初的写法:

module mymodule {
  // 直接依赖SLF4J核心模块
  requires org.slf4j;
  // 若代码直接使用Log4J API,需添加以下声明(可选)
  requires org.apache.logging.log4j;
  requires org.apache.logging.log4j.slf4j;
}

3. 验证依赖传递

执行mvn dependency:tree查看依赖树,确认slf4j-api已被正确引入且版本一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 15:20:52