DDD分层架构的应用

2021-05-01  本文已影响0人  晴天哥_王志

开篇

架构规范

对比我们日常spring mvc模式的分层架构,我们能够发现本质上MVC就是在践行DDD的分层架构,但不是每个使用mvc分层架构的实现都有明确的分层边界定义,不是每个使用mvc分层架构的实现都定义了每层使用的领域对象。

所以在原来的基础上定义每层的业务边界和数据边界就是更好的应用分层实现业务扩展

分层架构

服务层定义

数据层定义

Api层异常处理

@PostMapping("checkout")
public Result<OrderDTO> checkout(Long itemId, Integer quantity) {
    try {
        CheckoutCommand cmd = new CheckoutCommand();
        OrderDTO orderDTO = checkoutService.checkout(cmd);    
        return Result.success(orderDTO);
    } catch (ConstraintViolationException cve) {
        // 捕捉一些特殊异常,比如Validation异常
        return Result.fail(cve.getMessage());
    } catch (Exception e) {
        // 兜底异常捕获
        return Result.fail(e.getMessage());
    }
}
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ResultHandler {

}

@Aspect
@Component
public class ResultAspect {
    @Around("@annotation(ResultHandler)")
    public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
        Object proceed = null;
        try {
            proceed = joinPoint.proceed();
        } catch (ConstraintViolationException cve) {
            return Result.fail(cve.getMessage());
        } catch (Exception e) {
            return Result.fail(e.getMessage());
        }
        return proceed;
    }
}

总结

参考

上一篇 下一篇

猜你喜欢

热点阅读