多模块 Spring 项目构建
在一个多模块的 Spring 项目中,父模块通常被定义为一个 pom.xml
文件,包含所有子模块的公共配置、依赖和插件。子模块通过继承父模块的 pom.xml
文件,来共享和管理这些公共依赖和版本信息。
实现步骤
-
创建父模块(Parent Module):
- 在父模块的
pom.xml
中,定义所有的依赖管理和版本控制。 - 确保
<packaging>
类型设置为pom
,因为父模块不需要生成 JAR 或 WAR 文件。
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.example</groupId> <artifactId>parent-module</artifactId> <version>1.0.0</version> <packaging>pom</packaging> <modules> <module>module-a</module> <module>module-b</module> </modules> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>3.1.0</version> </dependency> <!-- 其他依赖 --> </dependencies> </dependencyManagement> <properties> <!-- 定义共享版本 --> <spring.boot.version>3.1.0</spring.boot.version> <!-- 其他属性 --> </properties> <dependencies> <!-- 子模块公共依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <!-- 其他依赖 --> </dependencies> <build> <plugins> <!-- 共享插件配置 --> </plugins> </build> </project>
- 在父模块的
-
创建子模块(Submodules):
- 在每个子模块的
pom.xml
中,继承父模块的配置。
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>com.example</groupId> <artifactId>parent-module</artifactId> <version>1.0.0</version> <relativePath>../pom.xml</relativePath> <!-- 指向父模块的相对路径 --> </parent> <artifactId>module-a</artifactId> <dependencies> <!-- 使用父模块中定义的版本和依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> <build> <plugins> <!-- 如果需要,可以添加模块特有的插件 --> </plugins> </build> </project>
- 在每个子模块的
关键点
dependencyManagement
: 父模块中的dependencyManagement
标签下定义的依赖不会自动被子模块继承,但子模块可以声明这些依赖而不需要指定版本号,版本由父模块统一管理。dependencies
: 父模块中的dependencies
标签下定义的依赖会被子模块自动继承。relativePath
: 子模块中的<parent>
标签的relativePath
属性用于指定父模块的相对路径。
通过这种方式,父模块可以统一管理所有子模块的依赖版本,确保项目中所有模块使用一致的依赖版本。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
2023-08-10 Windows 10的IIS中设置虚拟目录后无法打开浏览
2022-08-10 Docker安装步骤