
在 Java 9+ 模块系统中,requires 语句必须引用模块名(module name)而非 Maven 坐标或包名;Caffeine 的实际模块名为 com.github.benmanes.caffeine,而非 com.github.benmanes.caffeine.cache,且需确保 JAR 包含有效 module-info.class 并被正确解析为模块。
在 java 9+ 模块系统中,`requires` 语句必须引用**模块名(module name)**而非 maven 坐标或包名;caffeine 的实际模块名为 `com.github.benmanes.caffeine`,而非 `com.github.benmanes.caffeine.cache`,且需确保 jar 包含有效 `module-info.class` 并被正确解析为模块。
当你在 module-info.java 中写入:
module stock.core {
requires com.github.benmanes.caffeine.cache; // ❌ 错误:这不是模块名
}编译器会报错 Module not found: com.github.benmanes.caffeine.cache —— 因为 com.github.benmanes.caffeine.cache 是包名(package),不是模块名(module name)。
✅ 正确做法是查阅 Caffeine 官方 module-info.java 源码(见 GitHub),其首行明确声明:
module com.github.benmanes.caffeine { // ✅ 这才是真正的模块名
exports com.github.benmanes.caffeine;
exports com.github.benmanes.caffeine.cache;
// ... 其他 exports/opens/uses 等
}因此,你的 module-info.java 应改为:
立即学习“Java免费学习笔记(深入)”;
module stock.core {
requires com.github.benmanes.caffeine; // ✅ 正确模块名
// 如需使用 Cache 接口,还需确保该包已导出(它确实已导出,见上)
}⚠️ 同时务必满足以下三项前提条件,否则即使模块名正确仍会失败:
-
JAR 必须包含 module-info.class
Caffeine ≥ 2.9 已原生支持模块化(即 caffeine-3.1.6.jar 内含 META-INF/MANIFEST.MF 声明 Automatic-Module-Name 或根目录含 module-info.class)。可通过解压验证:jar -tf ~/.m2/repository/com/github/ben-manes/caffeine/caffeine/3.1.6/caffeine-3.1.6.jar | grep module-info # 应输出:module-info.class
-
Maven 项目需启用模块路径(而非仅类路径)
在 pom.xml 中显式配置 maven-compiler-plugin 使用 --module-path(JDK 9+ 默认行为,但需确认未被覆盖):<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.11.0</version> <configuration> <source>17</source> <target>17</target> <compilerArgs> <!-- 可选:显式启用模块系统诊断 --> <arg>--show-module-resolution</arg> </compilerArgs> </configuration> </plugin> IDE(如 IntelliJ IDEA)需同步 Maven 模块状态
即使 mvn compile 成功,IDE 可能缓存旧的类路径配置。务必执行:
→ 右键项目 → Maven → Reload project
或点击右上角 Maven 工具窗口 → 刷新图标(Reimport)
(你截图中的操作正是关键步骤:强制 IDE 重新解析 module-info.java 与依赖模块关系)
? 补充说明:
- 若你使用的是较老版本 Caffeine(<2.9),它不包含 module-info.class,此时 JVM 会为其生成自动模块名(Automatic Module Name),即 com.github.benmanes.caffeine(由 artifactId 推导),但仍不可写作 com.github.benmanes.caffeine.cache。
- requires 不支持“子模块”语法——Java 模块系统中不存在嵌套模块概念,com.github.benmanes.caffeine.cache 仅为包路径,不能作为 requires 目标。
- 若仍有问题,可在编译时添加 --show-module-resolution 参数,观察 JVM 如何解析和链接模块,快速定位缺失环节。
✅ 总结操作清单:
- ✅ 将 requires com.github.benmanes.caffeine.cache; 改为 requires com.github.benmanes.caffeine;
- ✅ 确认 caffeine-3.1.6.jar 内含 module-info.class
- ✅ 更新 maven-compiler-plugin 配置并指定 JDK 17
- ✅ 在 IDEA 中 Reimport Maven project(非简单刷新文件)
- ✅ 清理并重编译:mvn clean compile
完成以上步骤后,模块依赖即可被正确定位与链接,强封装目标方可落地。

















