1. 洋葱架构核心层次
应用层 (Application)
↑
领域层 (Domain) ← 基础设施层 (Infrastructure)
1.1 标准分层(从内到外)
领域模型层(Domain Model) - 最内层,包含实体、值对象、聚合根、领域服务等
领域服务层(Domain Services) - 处理跨聚合的业务逻辑
应用服务层(Application Services) - 协调领域对象完成用例
接口适配层(Interface Adapters) - 控制器、DTO转换等
基础设施层(Infrastructure) - 最外层,数据库、消息队列等实现
2. Java实现示例
项目结构
src/main/java
├── com
│ └── example
│ ├── application // 应用层
│ ├── domain // 领域层
│ │ ├── model // 领域模型
│ │ ├── repository // 仓储接口
│ │ └── service // 领域服务
│ ├── infrastructure // 基础设施层
│ └── interfaces // 接口层
2.1 领域模型实现
// 聚合根示例
package com.example.domain.model;
public class Order {
private OrderId id;
private CustomerId customerId;
private List<OrderItem> items;
private OrderStatus status;
// 领域行为
public void addItem(ProductId productId, int quantity, Money price) {
// 业务规则验证
if (status != OrderStatus.DRAFT) {
throw new IllegalStateException("Cannot add items to a confirmed order");
}
items.add(new OrderItem(productId, quantity, price));
}
public void confirm() {
if (items.isEmpty()) {
throw new IllegalStateException("Cannot confirm an empty order");
}
status = OrderStatus.CONFIRMED;
// 可以在这里发布领域事件
}
// 值对象示例
public static class OrderItem {
private final ProductId productId;
private final int quantity;
private final Money price;
// 构造函数、getters等
}
}
2.2 领域服务
package com.example.domain.service;
public class OrderService {
private final OrderRepository orderRepository;
private final PaymentService paymentService;
public OrderService(OrderRepository orderRepository, PaymentService paymentService) {
this.orderRepository = orderRepository;
this.paymentService = paymentService;
}
public void processOrderPayment(OrderId orderId, PaymentDetails paymentDetails) {
Order order = orderRepository.findById(orderId)
.orElseThrow(() -> new OrderNotFoundException(orderId));
if (order.getStatus() != OrderStatus.CONFIRMED) {
throw new IllegalStateException("Order must be confirmed before payment");
}
PaymentResult result = paymentService.processPayment(
order.getTotalAmount(),
paymentDetails);
if (result.isSuccess()) {
order.markAsPaid();
orderRepository.save(order);
} else {
throw new PaymentFailedException(result.getReason());
}
}
}
2.3 应用服务
package com.example.application;
public class OrderApplicationService {
private final OrderService orderService;
private final OrderRepository orderRepository;
public OrderApplicationService(OrderService orderService,
OrderRepository orderRepository) {
this.orderService = orderService;
this.orderRepository = orderRepository;
}
@Transactional
public void createOrder(CreateOrderCommand command) {
Order order = new Order(command.getCustomerId());
command.getItems().forEach(item ->
order.addItem(item.getProductId(), item.getQuantity(), item.getPrice()));
order.confirm();
orderRepository.save(order);
}
@Transactional
public void payOrder(PayOrderCommand command) {
orderService.processOrderPayment(
command.getOrderId(),
command.getPaymentDetails());
}
}
2.4 基础设施实现
package com.example.infrastructure.persistence;
@Repository
public class JpaOrderRepository implements OrderRepository {
private final OrderJpaRepository jpaRepository;
@Override
public Optional<Order> findById(OrderId id) {
return jpaRepository.findById(id.getValue())
.map(this::toDomain);
}
@Override
public void save(Order order) {
OrderEntity entity = toEntity(order);
jpaRepository.save(entity);
}
// 转换方法...
}
2.5 接口适配层
package com.example.interfaces.rest;
@RestController
@RequestMapping("/orders")
public class OrderController {
private final OrderApplicationService orderApplicationService;
@PostMapping
public ResponseEntity<?> createOrder(@RequestBody CreateOrderRequest request) {
CreateOrderCommand command = toCommand(request);
orderApplicationService.createOrder(command);
return ResponseEntity.accepted().build();
}
@PostMapping("/{id}/payments")
public ResponseEntity<?> payOrder(
@PathVariable String id,
@RequestBody PayOrderRequest request) {
PayOrderCommand command = new PayOrderCommand(
new OrderId(id),
new PaymentDetails(request.getCardNumber(), request.getAmount()));
orderApplicationService.payOrder(command);
return ResponseEntity.ok().build();
}
}
3. 依赖注入配置
@Configuration
public class AppConfig {
@Bean
public OrderRepository orderRepository(OrderJpaRepository jpaRepository) {
return new JpaOrderRepository(jpaRepository);
}
@Bean
public OrderService orderService(
OrderRepository orderRepository,
PaymentService paymentService) {
return new OrderService(orderRepository, paymentService);
}
@Bean
public OrderApplicationService orderApplicationService(
OrderService orderService,
OrderRepository orderRepository) {
return new OrderApplicationService(orderService, orderRepository);
}
}
4. 洋葱架构关键原则
依赖方向:内层不依赖外层,外层依赖内层
领域模型纯净:领域层不依赖任何基础设施
接口隔离:通过接口定义依赖关系
依赖注入:通过DI容器管理依赖关系
5. 优势与适用场景
优势
业务逻辑高度内聚
技术细节与业务分离
易于测试和维护
技术栈更换成本低
适用场景
复杂业务系统
长期演进的项目
需要多团队协作的大型项目
6. 常见问题解决方案
Q: 如何处理跨聚合的事务?
A: 使用领域事件+最终一致性,或者应用层的@Transactional
Q: 如何避免贫血模型?
A: 确保领域对象包含业务行为,而不仅仅是getter/setter
Q: 基础设施如何访问领域模型?
A: 通过仓储接口,由基础设施层实现具体持久化逻辑
7. 依赖注入最佳实践
@Service
public class OrderService {
private final OrderRepository orderRepository;
private final PaymentService paymentService;
public OrderService(OrderRepository orderRepository,
PaymentService paymentService) {
this.orderRepository = orderRepository;
this.paymentService = paymentService;
}
}
改进说明
移除冗余的@Autowired注解:
从Spring 4.3开始,单个构造器的情况下会自动注入,不需要显式@Autowired
更简洁,减少样板代码
添加@Service注解:
明确标识这是一个Spring管理的服务组件
使类更容易被组件扫描发现
保持final字段:
确保依赖不可变
帮助识别未初始化的依赖
线程安全
参数校验(可选增强):
public OrderService(OrderRepository orderRepository,
PaymentService paymentService) {
this.orderRepository = Objects.requireNonNull(orderRepository,
"OrderRepository must not be null");
this.paymentService = Objects.requireNonNull(paymentService,
"PaymentService must not be null");
}
在开发早期捕获可能的注入失败
提供更清晰的错误信息
为什么这是最佳实践?
不可变性:final字段确保依赖关系在构造后不会改变
明确性:一眼就能看出类的所有依赖
可测试性:无需Spring容器也能轻松实例化和测试
单一职责:构造器只做初始化,不包含业务逻辑
Spring推荐:符合Spring团队官方推荐的做法
其他注意事项
多个构造器情况:
如果有多个构造器,需要在想要使用的构造器上添加@Autowired
但通常建议保持单个构造器
Lombok简化(可选):
@Service
@RequiredArgsConstructor
public class OrderService {
private final OrderRepository orderRepository;
private final PaymentService paymentService;
}
使用Lombok自动生成构造器
争议点:部分团队偏好显式代码
循环依赖警示:
构造器注入会立即暴露循环依赖问题
这是优点而非缺点,促使更好的设计
8. 订单状态变更时更新库存的实现方案
项目包结构
src/main/java/com/example/order/
├── application/
├── domain/
│ ├── event/
│ │ ├── DomainEvent.java
│ │ ├── OrderConfirmedEvent.java
│ │ ├── OrderCancelledEvent.java
│ │ └── publisher/
│ │ ├── DomainEventPublisher.java
│ │ └── SimpleDomainEventPublisher.java
│ ├── model/
│ │ ├── Order.java
│ │ ├── OrderItem.java
│ │ └── OrderStatus.java
│ └── service/
│ └── OrderService.java
├── infrastructure/
│ ├── event/
│ │ └── handler/
│ │ ├── InventoryUpdateHandler.java
│ │ └── OrderEventCompensator.java
│ └── persistence/
└── interfaces/
核心类实现
1. 基础领域事件接口
// domain/event/DomainEvent.java
package com.example.order.domain.event;
import java.time.LocalDateTime;
public interface DomainEvent {
LocalDateTime occurredOn();
}
2. 订单相关领域事件
// domain/event/OrderConfirmedEvent.java
package com.example.order.domain.event;
import com.example.order.domain.model.OrderId;
import com.example.order.domain.model.OrderItem;
import java.time.LocalDateTime;
import java.util.List;
public class OrderConfirmedEvent implements DomainEvent {
private final OrderId orderId;
private final List<OrderItem> items;
private final LocalDateTime occurredOn;
public OrderConfirmedEvent(OrderId orderId, List<OrderItem> items) {
this.orderId = orderId;
this.items = List.copyOf(items);
this.occurredOn = LocalDateTime.now();
}
// Getters...
@Override
public LocalDateTime occurredOn() {
return occurredOn;
}
}
// domain/event/OrderCancelledEvent.java
package com.example.order.domain.event;
import com.example.order.domain.model.OrderId;
import com.example.order.domain.model.OrderItem;
import java.time.LocalDateTime;
import java.util.List;
public class OrderCancelledEvent implements DomainEvent {
private final OrderId orderId;
private final List<OrderItem> items;
private final LocalDateTime occurredOn;
// 类似OrderConfirmedEvent的实现
}
3. 领域事件发布器实现
// domain/event/publisher/DomainEventPublisher.java
package com.example.order.domain.event.publisher;
import com.example.order.domain.event.DomainEvent;
public interface DomainEventPublisher {
void publish(DomainEvent event);
void registerSubscriber(Class<?> eventType, DomainEventSubscriber subscriber);
}
@FunctionalInterface
public interface DomainEventSubscriber {
void handleEvent(DomainEvent event);
}
// domain/event/publisher/SimpleDomainEventPublisher.java
package com.example.order.domain.event.publisher;
import com.example.order.domain.event.DomainEvent;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Component
public class SimpleDomainEventPublisher implements DomainEventPublisher {
private final Map<Class<?>, List<DomainEventSubscriber>> subscribers = new HashMap<>();
@Override
public void publish(DomainEvent event) {
Class<?> eventType = event.getClass();
if (subscribers.containsKey(eventType)) {
subscribers.get(eventType).forEach(subscriber -> {
try {
subscriber.handleEvent(event);
} catch (Exception e) {
// 记录错误并继续处理其他订阅者
System.err.println("Error handling event: " + e.getMessage());
// 可以在这里触发补偿机制
EventCompensationQueue.addFailedEvent(event, subscriber);
}
});
}
}
@Override
public void registerSubscriber(Class<?> eventType, DomainEventSubscriber subscriber) {
subscribers.computeIfAbsent(eventType, k -> new ArrayList<>()).add(subscriber);
}
}
4. 订单聚合根实现
// domain/model/Order.java
package com.example.order.domain.model;
import com.example.order.domain.event.DomainEventPublisher;
import com.example.order.domain.event.OrderConfirmedEvent;
import com.example.order.domain.event.OrderCancelledEvent;
import java.util.List;
public class Order {
private OrderId id;
private List<OrderItem> items;
private OrderStatus status;
// 构造函数等其他方法...
public void confirm() {
if (this.status != OrderStatus.PENDING) {
throw new IllegalStateException("只有待确认订单才能确认");
}
this.status = OrderStatus.CONFIRMED;
DomainEventPublisher.instance()
.publish(new OrderConfirmedEvent(this.id, this.items));
}
public void cancel() {
// 取消逻辑...
DomainEventPublisher.instance()
.publish(new OrderCancelledEvent(this.id, this.items));
}
}
5. 库存更新处理器
// infrastructure/event/handler/InventoryUpdateHandler.java
package com.example.order.infrastructure.event.handler;
import com.example.order.domain.event.OrderConfirmedEvent;
import com.example.order.domain.event.OrderCancelledEvent;
import com.example.order.domain.event.publisher.DomainEventSubscriber;
import com.example.order.infrastructure.persistence.InventoryRepository;
import org.springframework.stereotype.Component;
@Component
public class InventoryUpdateHandler implements DomainEventSubscriber {
private final InventoryRepository inventoryRepository;
public InventoryUpdateHandler(InventoryRepository inventoryRepository) {
this.inventoryRepository = inventoryRepository;
// 注册自己为事件订阅者
DomainEventPublisher.instance()
.registerSubscriber(OrderConfirmedEvent.class, this);
DomainEventPublisher.instance()
.registerSubscriber(OrderCancelledEvent.class, this);
}
@Override
public void handleEvent(DomainEvent event) {
if (event instanceof OrderConfirmedEvent) {
handle((OrderConfirmedEvent) event);
} else if (event instanceof OrderCancelledEvent) {
handle((OrderCancelledEvent) event);
}
}
private void handle(OrderConfirmedEvent event) {
event.getItems().forEach(item -> {
inventoryRepository.findByProductId(item.getProductId())
.ifPresent(inventory -> {
inventory.reduceStock(item.getQuantity());
inventoryRepository.save(inventory);
});
});
}
private void handle(OrderCancelledEvent event) {
// 类似OrderConfirmedEvent的处理
}
}
事件消费失败补偿机制
1. 补偿队列实现
// infrastructure/event/handler/EventCompensationQueue.java
package com.example.order.infrastructure.event.handler;
import com.example.order.domain.event.DomainEvent;
import com.example.order.domain.event.publisher.DomainEventSubscriber;
import java.util.concurrent.ConcurrentLinkedQueue;
public class EventCompensationQueue {
private static final ConcurrentLinkedQueue<FailedEvent> queue = new ConcurrentLinkedQueue<>();
public static void addFailedEvent(DomainEvent event, DomainEventSubscriber subscriber) {
queue.offer(new FailedEvent(event, subscriber));
}
public static void processFailedEvents() {
FailedEvent failedEvent;
while ((failedEvent = queue.poll()) != null) {
try {
failedEvent.subscriber().handleEvent(failedEvent.event());
} catch (Exception e) {
// 仍然失败,可以记录到持久化存储
System.err.println("Compensation failed for event: " + failedEvent.event());
PersistentEventLogger.logFailedEvent(failedEvent);
}
}
}
record FailedEvent(DomainEvent event, DomainEventSubscriber subscriber) {}
}
2. 补偿处理器
// infrastructure/event/handler/OrderEventCompensator.java
package com.example.order.infrastructure.event.handler;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class OrderEventCompensator {
@Scheduled(fixedDelay = 60000) // 每分钟执行一次
public void compensateFailedEvents() {
EventCompensationQueue.processFailedEvents();
}
}
3. 持久化失败事件(可选)
// infrastructure/event/handler/PersistentEventLogger.java
package com.example.order.infrastructure.event.handler;
import com.example.order.domain.event.DomainEvent;
import com.example.order.infrastructure.persistence.FailedEventRepository;
public class PersistentEventLogger {
private static FailedEventRepository repository;
public static void initialize(FailedEventRepository repository) {
PersistentEventLogger.repository = repository;
}
public static void logFailedEvent(EventCompensationQueue.FailedEvent failedEvent) {
if (repository != null) {
repository.save(new FailedEventEntity(
failedEvent.event(),
failedEvent.subscriber().getClass().getName()
));
}
}
}
完整工作流程
订单状态变更:调用order.confirm()或order.cancel()
事件发布:订单聚合发布OrderConfirmedEvent或OrderCancelledEvent
事件处理:
InventoryUpdateHandler接收事件并更新库存
如果失败,事件进入补偿队列
补偿机制:
每分钟尝试重新处理失败事件
仍然失败的事件被持久化记录
人工干预:对于持久化的失败事件,可以提供管理界面进行人工处理
增强建议
引入消息队列:对于生产环境,可以用Kafka或RabbitMQ替换简单的内存发布器
增加重试策略:为补偿机制增加指数退避重试
监控报警:对持续失败的事件设置报警
事务管理:考虑使用Spring的@TransactionalEventListener实现事务边界控制