COLA架构避坑指南:我在电商项目中遇到的5个分层设计陷阱

当我们的电商团队决定从传统MVC架构转向COLA架构时,原本期待它能带来更好的领域模型表达和系统可维护性。但在实际落地过程中,我们踩了不少坑。本文将分享我们在分层设计上的五个典型误区,以及如何通过调整架构规避这些问题。

1. Adapter层与Infrastructure层的职责混淆

在COLA架构中,Adapter层负责处理外部请求的适配,而Infrastructure层则专注于技术细节的实现。但在初期实践中,我们经常混淆两者的职责。

典型错误表现:

  • 在Controller(Adapter层)中直接调用MyBatis Mapper(Infrastructure层)
  • 将RPC客户端实现代码放在Adapter层的DTO转换逻辑中
  • 在Adapter层处理缓存逻辑
// 错误示例:Controller中直接操作数据库
@RestController
public class OrderController {
    @Autowired
    private OrderMapper orderMapper;  // Infrastructure层组件
    
    @PostMapping("/orders")
    public Result createOrder(@RequestBody OrderDTO orderDTO) {
        OrderDO orderDO = convertToDO(orderDTO);
        orderMapper.insert(orderDO);  // 直接调用Infrastructure层
        return Result.success();
    }
}

正确做法:

  1. Adapter层只应包含:

    • 协议转换(HTTP/RPC等)
    • 参数校验
    • 基本数据格式转换
  2. Infrastructure层应包含:

    • 数据库访问实现
    • 缓存实现
    • 外部服务调用实现
// 正确示例:通过Application层中转
@RestController
public class OrderController {
    @Autowired
    private OrderApplicationService orderAppService;
    
    @PostMapping("/orders")
    public Result createOrder(@RequestBody OrderDTO orderDTO) {
        return orderAppService.createOrder(orderDTO);
    }
}

提示:可以通过代码静态检查工具限制Adapter层对Infrastructure层组件的直接引用

2. 领域服务臃肿:沦为事务脚本的温床

领域层本应是业务逻辑的核心载体,但我们经常犯的错误是把Domain Service写成"上帝服务"。

问题症状:

  • 单个Domain Service方法超过200行代码
  • 方法中包含大量if-else分支
  • 需要频繁注入多个Repository
// 问题代码:臃肿的领域服务
@Service
public class OrderDomainServiceImpl implements OrderDomainService {
    @Autowired
    private OrderRepository orderRepo;
    @Autowired
    private ProductRepository productRepo;
    @Autowired
    private UserRepository userRepo;
    
    public void placeOrder(Order order) {
        // 校验用户
        User user = userRepo.findById(order.getUserId());
        if(user == null) throw new BizException("用户不存在");
        if(user.isDisabled()) throw new BizException("用户已被禁用");
        
        // 校验商品
        for(OrderItem item : order.getItems()) {
            Product product = productRepo.findById(item.getProductId());
            if(product == null) throw new BizException("商品不存在");
            if(product.getStock() < item.getQuantity()) {
                throw new BizException("库存不足");
            }
        }
        
        // 计算价格
        BigDecimal totalAmount = calculateTotal(order);
        order.setTotalAmount(totalAmount);
        
        // 保存订单
        orderRepo.save(order);
        
        // 扣减库存
        for(OrderItem item : order.getItems()) {
            productRepo.reduceStock(item.getProductId(), item.getQuantity());
        }
        
        // 发送事件
        eventPublisher.publish(new OrderCreatedEvent(order));
    }
}

优化方案:

  1. 将业务逻辑下沉到聚合根
  2. 使用领域事件解耦流程
  3. 引入Specification模式封装业务规则
// 优化后的领域服务
@Service
public class OrderDomainServiceImpl implements OrderDomainService {
    @Autowired
    private OrderRepository orderRepo;
    
    public void placeOrder(Order order) {
        // 委托聚合根处理核心逻辑
        order.place();
        orderRepo.save(order);
    }
}

// 聚合根中的业务逻辑
public class Order {
    public void place() {
        validateUser();
        validateProducts();
        calculateTotal();
    }
    
    private void validateUser() {
        // 用户校验逻辑
    }
    
    private void validateProducts() {
        // 商品校验逻辑
    }
}

3. 基础设施层越界:技术实现污染业务逻辑

Infrastructure层应该保持"技术实现细节"的定位,但我们经常让它承担了不该有的职责。

常见反模式:

  • 在Mapper中编写复杂业务逻辑SQL
  • 在RPC客户端中处理业务异常
  • 缓存实现细节暴露到领域层
<!-- 问题示例:Mapper中实现业务逻辑 -->
<select id="findActiveOrders" resultType="OrderDO">
    SELECT * FROM orders 
    WHERE status NOT IN ('CANCELLED', 'COMPLETED')
    AND created_time > DATE_SUB(NOW(), INTERVAL 30 DAY)
    ORDER BY 
        CASE WHEN priority = 'HIGH' THEN 0 ELSE 1 END,
        created_time DESC
</select>

解决方案对比表:

问题点错误做法正确做法
复杂查询在Mapper写业务逻辑使用QueryService或CQRS模式
异常处理在RPC客户端转换业务异常统一异常拦截器处理
缓存策略领域层直接操作缓存通过Repository接口隐藏
// 基础设施层的正确实现示例
@Repository
public class OrderRepositoryImpl implements OrderRepository {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private CacheTemplate cacheTemplate;
    
    @Override
    public Order findById(Long id) {
        return cacheTemplate.get(
            "order:" + id, 
            () -> orderMapper.selectById(id)
        );
    }
}

4. 应用层过度膨胀:沦为第二个领域层

Application层本应是薄层,仅负责流程编排,但我们经常让它承担了太多责任。

典型问题:

  • 应用服务方法包含业务规则判断
  • 在Application层实现数据转换逻辑
  • 跨聚合的业务逻辑放在应用层
// 问题代码:臃肿的应用服务
@Service
public class OrderAppServiceImpl implements OrderAppService {
    public OrderDTO createOrder(OrderCreateCommand command) {
        // 参数校验
        if(command.getItems() == null || command.getItems().isEmpty()) {
            throw new ValidationException("订单项不能为空");
        }
        
        // 业务校验
        User user = userService.getUser(command.getUserId());
        if(user.getLevel() < 1) {
            throw new BizException("用户等级不足");
        }
        
        // 领域逻辑
        List<Product> products = productService.getProducts(
            command.getItems().stream()
                .map(OrderItemCommand::getProductId)
                .collect(Collectors.toList())
        );
        
        BigDecimal totalAmount = calculateTotal(products, command.getItems());
        
        // 对象转换
        Order order = convertToDomain(command, totalAmount);
        
        // 调用领域服务
        orderDomainService.placeOrder(order);
        
        // 返回DTO
        return convertToDTO(order);
    }
}

精简策略:

  1. 使用Command对象封装入参
  2. 引入Converter处理对象转换
  3. 将业务规则下沉到领域层
// 优化后的应用服务
@Service
@RequiredArgsConstructor
public class OrderAppServiceImpl implements OrderAppService {
    private final OrderDomainService orderDomainService;
    private final OrderConverter orderConverter;
    
    public OrderResult createOrder(OrderCreateCommand command) {
        Order order = orderConverter.toDomain(command);
        orderDomainService.placeOrder(order);
        return orderConverter.toResult(order);
    }
}

5. 层间依赖混乱:破坏架构的整洁性

COLA架构强调分层单向依赖,但实践中经常出现循环依赖或反向依赖。

依赖关系对比:

正确依赖方向常见错误依赖
Adapter → Application → Domain ← InfrastructureApplication直接调用Infrastructure
Domain不依赖任何外层Domain层引入Spring注解
Infrastructure实现Domain定义的接口Infrastructure接口定义在Application层

解决方案:

  1. 使用依赖注入框架检查层间依赖
  2. 建立模块化工程结构
  3. 定义清晰的接口契约

Maven模块配置示例:

<!-- parent pom.xml -->
<modules>
    <module>order-adapter</module>
    <module>order-application</module>
    <module>order-domain</module>
    <module>order-infrastructure</module>
</modules>

<!-- order-domain/pom.xml -->
<dependencies>
    <!-- 领域层不依赖其他模块 -->
</dependencies>

<!-- order-application/pom.xml -->
<dependencies>
    <dependency>
        <groupId>com.example</groupId>
        <artifactId>order-domain</artifactId>
    </dependency>
</dependencies>

关键检查点:

  • Domain模块不应有Spring相关依赖
  • Infrastructure只被Application或Adapter依赖
  • 跨层调用必须通过接口

在电商履约系统的重构过程中,通过修正这五个分层设计问题,我们的代码结构变得清晰,各层职责分明。特别是订单核心域的修改维护成本降低了约40%,新功能的开发速度提升了25%。COLA架构的真正价值在于约束,而好的约束来自于对分层原则的严格遵守。

Logo

电商企业物流数字化转型必备!快递鸟 API 接口,72 小时快速完成物流系统集成。全流程实战1V1指导,营造开放的API技术生态圈。

更多推荐