Maven创建子模块
Maven创建子模块
在一个多模块的Maven项目中,通常使用<module>
标签在父POM(Project Object Model)文件中来定义子模块。
这样可以将多个Maven项目组织在一起,使它们成为一个整体的构建单元。
如何定义子模块
- 首先,创建一个父项目的POM文件
pom.xml
,其中包含所有子模块的定义:
1 | <project xmlns="http://maven.apache.org/POM/4.0.0" |
- 然后,在父项目目录下创建子模块目录,例如
api
、service
和web
。每个子模块目录中都需要有一个pom.xml
文件。
例如,api
模块的pom.xml
文件:
1 | <project xmlns="http://maven.apache.org/POM/4.0.0" |
- 其他子模块(例如
service
和web
)的pom.xml
文件类似,只需更改<artifactId>
即可。
通过这种方式,父POM中的子模块可以通过<module>
标签联系在一起,Maven会在构建父项目时自动构建所有子模块。子模块默认继承了父模块的依赖
模块间依赖冲突
依赖版本冲突
不同模块可能依赖同一个库的不同版本,这可能导致类加载冲突和运行时错误。
解决方法:
Dependency Management
在父 pom.xml 中使用
<dependencyManagement>
标签来统一管理依赖的版本。子模块可以继承这些版本定义,从而避免冲突。
1
2
3
4
5
6
7
8
9<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.example</groupId>
<artifactId>example-lib</artifactId>
<version>1.2.3</version>
</dependency>
</dependencies>
</dependencyManagement>
冲突的传递依赖
A模块依赖B模块,B模块又依赖C模块的不同版本,这可能导致A模块在运行时遇到依赖冲突。
解决方法:
Exclusions
在依赖中使用
<exclusions>
标签来排除特定的传递依赖。1
2
3
4
5
6
7
8
9
10
11<dependency>
<groupId>org.example</groupId>
<artifactId>example-lib</artifactId>
<version>1.2.3</version>
<exclusions>
<exclusion>
<groupId>org.other</groupId>
<artifactId>other-lib</artifactId>
</exclusion>
</exclusions>
</dependency>
重复的依赖
多个模块直接依赖同一个库,这可能导致重复下载和类路径冗余。
解决方法:
统一依赖声明
在父 pom.xml 中统一声明依赖,子模块直接继承。
1
2
3
4
5
6
7<dependencies>
<dependency>
<groupId>org.example</groupId>
<artifactId>example-lib</artifactId>
<version>1.2.3</version>
</dependency>
</dependencies>
依赖范围冲突
依赖的范围(如compile
、test
、provided
)也可能在不同模块间产生冲突。
解决方法:
正确设置依赖范围
确保在每个模块中正确设置依赖的范围,避免不必要的依赖被引入到最终的构建产物中。
1
2
3
4
5
6<dependency>
<groupId>org.example</groupId>
<artifactId>example-lib</artifactId>
<version>1.2.3</version>
<scope>test</scope>
</dependency>
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 CautionX!