跳到正文
Joeplover
后端开发·2025-11-25·约 3 分钟阅读

hmall 电商项目:多模块 Spring Boot 商城系统

多模块 Spring Boot 电商项目,涵盖用户、商品、购物车、订单、支付等完整电商功能,集成 JWT 认证与安全配置。

多模块电商

hmall 电商项目:多模块 Spring Boot 商城系统

从单体到多模块

hmall 是一个多模块 Spring Boot 电商项目,它解决的核心问题是:当项目代码膨胀到一定程度后,如何组织代码才能保证可维护性。

为什么要多模块

一个电商系统通常包括:商品、订单、用户、支付、物流、优惠券等模块。如果所有代码放在一个模块中:

src/main/java/com/hmall/
├── controller/
│   ├── ProductController.java
│   ├── OrderController.java
│   ├── UserController.java
│   └── ... (50+ 个 Controller)
├── service/
├── mapper/
├── entity/
└── config/

随着功能增加,一个模块会变成一个大泥球——编译慢(5 分钟起步)、耦合高(改订单影响商品)、分工难(多人改同一个模块经常冲突)。

多模块拆分

hmall/
├── hmall-parent/        # 父模块:统一管理依赖版本
├── hmall-common/        # 公共模块:DTO、工具类、常量
├── hmall-product/       # 商品模块:商品 CRUD、分类、品牌
├── hmall-order/         # 订单模块:订单流程、购物车
├── hmall-user/          # 用户模块:注册登录、地址管理
├── hmall-pay/           # 支付模块:支付回调、退款
└── hmall-gateway/       # 网关模块:路由转发、鉴权

模块职责划分

<!-- parent 管理所有模块的版本 -->
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>3.2.0</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
<!-- common 模块被所有业务模块依赖 -->
<dependencies>
    <dependency>
        <groupId>com.hmall</groupId>
        <artifactId>hmall-common</artifactId>
        <version>${project.version}</version>
    </dependency>
</dependencies>

模块间通信

// 订单模块依赖商品模块的接口(不是实现)
// hmall-order/pom.xml
<dependency>
    <groupId>com.hmall</groupId>
    <artifactId>hmall-product-api</artifactId>  // 只依赖 API 接口,不依赖实现
</dependency>

// 商品模块提供接口
// hmall-product-api
public interface ProductService {
    ProductDTO getById(Long id);
    boolean deductStock(Long productId, Integer quantity);
}

关键原则:业务模块之间只依赖接口(API 模块),不直接依赖实现。这样商品模块改了实现,订单模块不需要重新编译。

构建顺序

# 必须按依赖顺序构建
mvn clean install -pl hmall-common -am   # 先构建 common
mvn clean install -pl hmall-product -am  # 再构建 product
mvn clean install                         # 最后构建整个项目

使用 -am(also make)参数自动处理依赖顺序。

多模块 vs 微服务

维度多模块微服务
部署一个 JAR多个 JAR
通信方法调用RPC/HTTP
数据库共享一个数据库每个服务独立数据库
运维单点部署需要服务治理

多模块是代码层面的拆分,微服务是部署层面的拆分。先做好多模块设计,如果以后需要拆微服务,按模块边界自然地独立部署即可。