贫血模型(传统三层架构):
// 贫血模型:对象只是数据容器,逻辑在Service中
public class Order {
private Long id;
private String status; // 状态是String,没有约束
private List<OrderItem> items;
// 只有getter/setter,没有业务逻辑
}
// 业务逻辑散落在Service中
public class OrderService {
public void cancelOrder(Order order) {
if ("PAID".equals(order.getStatus())) { // 状态判断在Service
order.setStatus("CANCELLED"); // 直接修改字段
refundService.refund(order); // 退款逻辑在外部
}
}
}
充血模型(DDD推荐):
// 充血模型:对象封装数据和行为
public class Order {
private Long id;
private OrderStatus status; // 枚举,类型安全
private List<OrderItem> items;
private Money totalAmount;
// 业务逻辑内聚在实体中
public void cancel() {
if (status != OrderStatus.PAID) {
throw new DomainException("只有已支付订单可取消");
}
this.status = OrderStatus.CANCELLED;
// 发布领域事件
DomainEventPublisher.publish(new OrderCancelledEvent(this.id, this.totalAmount));
}
public void addItem(Product product, int quantity) {
if (status != OrderStatus.CREATED) {
throw new DomainException("只有待支付订单可添加商品");
}
items.add(new OrderItem(product, quantity));
recalculateTotal();
}
private void recalculateTotal() {
this.totalAmount = items.stream()
.map(OrderItem::getSubtotal)
.reduce(Money.ZERO, Money::add);
}
}
对比:
贫血模型 充血模型
───────────────────────────────────────────────────
逻辑位置 Service层 领域对象内部
对象职责 数据容器 数据+行为
封装性 差(可随意修改字段) 好(通过方法约束)
代码重复 多个Service操作同一实体 逻辑内聚,无重复
测试难度 需要Mock大量依赖 可独立测试领域对象
适用场景 简单CRUD 复杂业务逻辑
┌─────────────────────────────────────────────────┐
│ 聚合根(Aggregate Root) │
│ ┌─────────────────────────────────────────┐ │
│ │ Order (聚合根/实体) │ │
│ │ ├── id: Long │ │
│ │ ├── status: OrderStatus │ │
│ │ ├── shippingAddress: Address(值对象) │ │
│ │ │ │ │
│ │ ├── OrderItem(实体) │ │
│ │ │ ├── productId: Long │ │
│ │ │ ├── quantity: int │ │
│ │ │ └── price: Money(值对象) │ │
│ │ │ │ │
│ │ ├── OrderItem(实体) │ │
│ │ │ └── ... │ │
│ │ │ │ │
│ │ └── totalAmount: Money(值对象) │ │
│ └─────────────────────────────────────────┘ │
│ │
│ 对外只通过聚合根ID引用: orderId │
│ 不直接引用内部实体: orderItemId │
└─────────────────────────────────────────────────┘
实体(Entity):有唯一标识,生命周期跨越多个操作
值对象(Value Object):无唯一标识,由属性值定义,不可变
// 值对象:不可变,通过属性判断相等
public class Money {
private final BigDecimal amount;
private final String currency;
public Money(BigDecimal amount, String currency) {
this.amount = amount;
this.currency = currency;
}
public Money add(Money other) {
return new Money(this.amount.add(other.amount), this.currency);
}
// 没有setter,创建新实例表示变更
}
聚合根(Aggregate Root):聚合的入口和一致性边界
领域事件(Domain Event):
// 领域事件:表示领域中已经发生的事情
public class OrderCreatedEvent implements DomainEvent {
private final Long orderId;
private final Long userId;
private final Money totalAmount;
private final LocalDateTime occurredOn;
}
// 发布与订阅
// 订单聚合根发布事件
order.cancel(); // 内部自动发布 OrderCancelledEvent
// 库存上下文订阅事件
@EventHandler
public void handle(OrderCreatedEvent event) {
inventoryService.reserveStock(event.getOrderId());
}
领域服务(Domain Service):
// 不属于任何实体的业务逻辑
public class PricingService {
// 依赖领域规则,不是简单CRUD
public Money calculateDiscount(Order order, CustomerLevel level) {
// 复杂的折扣计算规则
}
}
仓储(Repository):
// 仓储:持久化的抽象接口
public interface OrderRepository {
Order findById(Long id);
void save(Order order);
void delete(Order order);
}
// 基础设施层实现
@Repository
public class JpaOrderRepository implements OrderRepository {
@Autowired
private JpaOrderMapper jpaMapper;
@Override
public void save(Order order) {
// 领域模型 → 数据模型 转换
OrderPO po = OrderConverter.toPO(order);
jpaMapper.save(po);
}
}
1. 一致性边界原则
┌─────────────────┐
│ 聚合内:强一致 │ 一次事务只修改一个聚合
│ 聚合间:最终一致 │ 通过领域事件同步
└─────────────────┘
2. 最小聚合原则
聚合越小越好,只包含必须保持一致的属性
❌ Order包含完整User信息 → 聚合太大
✅ Order只持有userId引用 → 聚合精简
3. 通过ID引用其他聚合
❌ Order中包含完整User对象
✅ Order中只保存userId,需要时通过Repository加载
4. 单次事务只修改一个聚合
跨聚合操作通过领域事件 + Saga/消息驱动
┌──────────────────────────────────────────────┐
│ Interface(接口层) │
│ Controller / DTO /Assembler │
│ 接收请求、转换DTO、调用Application层 │
├──────────────────────────────────────────────┤
│ Application(应用层) │
│ ApplicationService / DTO / EventPublisher │
│ 编排领域对象、事务管理、安全认证 │
│ 不包含业务逻辑 │
├──────────────────────────────────────────────┤
│ Domain(领域层) │
│ Entity / ValueObject / AggregateRoot │
│ DomainService / Repository(接口) / DomainEvent│
│ 核心业务逻辑 │
├──────────────────────────────────────────────┤
│ Infrastructure(基础设施层) │
│ RepositoryImpl / MQ / Cache / ExternalAPI │
│ 具体技术实现 │
└──────────────────────────────────────────────┘
依赖方向:Interface → Application → Domain ← Infrastructure
关键:Domain层不依赖任何外层
┌─────────────────────────┐
│ │
REST ─────▶│ 左适配器(入站) │
gRPC ─────▶│ Controller/Consumer │
MQ ───────▶│ │
│ ┌─────────────┐ │
│ │ 应用服务 │ │
│ │ (用例编排) │ │
│ ├─────────────┤ │
│ │ 领域模型 │ │
│ │(实体/值对象) │ │
│ └─────────────┘ │
│ ┌─────────────┐ │
│ │ 端口(接口) │◀─────│─ DB
│ │ Repository │ │─ Redis
│ │ EventPort │ │─ MQ
│ └─────────────┘ │
│ │
│ 右适配器(出站) │───────▶ 外部服务
│ RepositoryImpl/MQ/HTTP │───────▶ 第三方API
└─────────────────────────┘
核心思想:领域模型在正中心,不依赖任何外部技术
端口 = 接口定义(领域层定义)
适配器 = 接口实现(基础设施层实现)
一个电商系统的限界上下文划分:
┌──────────────┐ ┌──────────────┐ ┌──────────────┐
│ 订单上下文 │ │ 库存上下文 │ │ 支付上下文 │
│ │ │ │ │ │
│ Order │ │ Inventory │ │ Payment │
│ OrderItem │ │ Stock │ │ Refund │
│ OrderRepo │ │ Warehouse │ │ PayChannel │
└──────┬───────┘ └──────┬───────┘ └──────┬───────┘
│ │ │
│ 上下文映射(Context Map) │
│ ┌─────────────────────────────┐ │
│ │ Order → Inventory: 预留库存 │ │
│ │ Order → Payment: 发起支付 │ │
│ │ Payment → Order: 支付回调 │ │
│ └─────────────────────────────┘ │
│ │ │
同一个"商品"在不同上下文中的含义不同:
- 订单上下文: OrderItem(商品快照+价格)
- 库存上下文: StockItem(SKU+数量)
- 搜索上下文: ProductDoc(名称+描述+属性)
限界上下文 → 微服务拆分边界
一个限界上下文 ≈ 一个微服务
1. 为什么DDD推荐值对象不可变?如果地址需要修改怎么处理?
2. 聚合之间为什么要通过ID引用而非直接持有对象引用?
3. 领域事件和MQ消息的区别是什么?领域事件一定需要MQ吗?
4. 四层架构中,如果Application层直接调用JPA的EntityManager,违反了什么原则?
5. 如何识别一个系统中的限界上下文?有哪些实践方法?