“Java 模块”通常指 Java 9 引入的 Module System(JPMS,Java Platform Module System)。下面从概念 → 配置方式 → 常见示例 → 构建工具配置系统讲一下。
Java 模块用于更严格地控制依赖和可见性,核心文件是:
module-info.java
一个模块 = 一组包 + 明确的依赖 + 导出的 API
src/
└── com.example.hello/
├── module-info.java
└── com/example/hello/
└── Main.java
module com.example.hello {
requires java.base; // 默认就有,可省略
exports com.example.hello;
}
package com.example.hello;
public class Main {
public static void main(String[] args) {
System.out.println("Hello Module");
}
}
module com.example.service { }
requires com.example.util;
exports com.example.service.api;
opens com.example.service.internal to com.example.test;
uses com.example.spi.Service;
provides com.example.spi.Service with com.example.impl.ServiceImpl;
javac -d out \
src/com.example.hello/module-info.java \
src/com.example.hello/com/example/hello/Main.java
java --module-path out --module com.example.hello/com.example.hello.Main
parent-project
├── pom.xml
├── module-a
│ └── pom.xml
└── module-b
└── pom.xml
<modules>
<module>module-a</module>
<module>module-b</module>
</modules>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<release>17</release>
</configuration>
</plugin>
</plugins>
</build>
并在 src/main/java/module-info.java 中声明模块。
⚠️ Spring Boot 默认不推荐 JPMS
module-info.javamodule-info.java✅ 正确姿势:
Maven Module ≠ Java Module
requires 对应模块
exports 对应包
opens package to module;
--add-opens / --add-exports
| 场景 | 建议 |
|---|---|
| 学习 JPMS | 写 module-info.java |
| 企业项目 | Maven 多模块 |
| Spring Boot | 不用 JPMS |
| 微服务 | Maven/Gradle 模块即可 |
如果你能告诉我:
我可以直接给你可运行模板。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。