使用ConstraintValidator校验起止日期价格存在性的方案咨询
问题解答
1. 是否可以使用ConstraintValidator实现startDate和endDate的价格存在性校验?
可以,具体有两种实现方案:
- 扩展现有
@ConsecutivePrices注解逻辑:在该注解对应的ConstraintValidator实现中,新增边界存在性校验步骤。校验器可以通过上下文获取getMonthlyPrices方法的入参startDate、endDate,遍历返回的Price列表检查是否存在对应日期的价格记录即可。 - 新增独立返回值校验注解:单独定义
@CheckPriceBoundary注解,作用在getMonthlyPrices方法的返回值上,专门实现边界存在性校验,和原有连续性校验逻辑解耦。
2. 是否需要在getAverageAnnualPrice方法内捕获MethodArgumentNotValidException?
不需要,原因如下:
MethodArgumentNotValidException是Controller层请求入参校验失败抛出的异常,Feign接口返回值校验失败抛出的是ConstraintViolationException,二者属于不同的异常类型。- 你的需求是边界价格缺失不属于错误场景,不需要触发校验失败的异常流程,直接返回null即可。如果通过ConstraintValidator校验边界缺失就抛异常,反而需要额外捕获处理,增加不必要的复杂度,更推荐直接在业务方法中做校验:
public BigDecimal getAverageAnnualPrice(Long productId, LocalDate startDate, LocalDate endDate) { List<Price> prices = priceServiceClient.getMonthlyPrices(productId, startDate, endDate); // 新增边界校验逻辑,若为月度维度匹配可调整为判断年月一致 boolean hasStartPrice = prices.stream().anyMatch(p -> p.getPriceDate().equals(startDate)); boolean hasEndPrice = prices.stream().anyMatch(p -> p.getPriceDate().equals(endDate)); if (!hasStartPrice || !hasEndPrice) { return null; } // 原有计算年平均价格逻辑 return averageMonthlyPrice; }
这种实现逻辑直观,不需要修改原有校验注解的逻辑,也不需要额外处理异常,维护成本更低。
内容的提问来源于stack exchange,提问作者user8297969
相关产品推荐
相关产品推荐

