問題:
項目中常用@Validate 或者 @Valid 去對接口的入參做參數校驗,
最近項目中遇到另外一種情況,僅使用注解似乎難以滿足需求:
例如:實際情況中需要針對channel字段做進一步校驗,如channel為1(也就是IOS),則需要進一步校驗appId字段不能為空
public class RechargeConfigDTO { @NotNull(message = "主鍵不能為空") private Integer dbId; /** * 金額 */ @NotNull(message = "金額不能為空") private BigDecimal nnAmount; /** * 客戶端 1.ios 2.android 3.nn web */ @NotNull(message = "xxx不能為空") @ApiModelProperty(value = "客戶端 1.ios 2.android 3.nn web") private Integer channel; /** * 客戶端為蘋果,該項必填 */ @ApiModelProperty(value = "客戶端為蘋果,該項必填") private String appId; }
這個問題本質上很好解決,項目代碼中使用if-else判斷類型即可,但非常不靈活,而且會污染業務代碼,因為這些參數本質上屬於入參校驗,不需要在業務層做過多的代碼參數校驗
這里提供了一個方法,即使用Validate的Api去做校驗,這里可以放置在入參DTO對象中,避免污染業務代碼
/** * 處理分組校驗:如果是IOS配置類型,需要再做一次校驗 */ public void handleValidateGroup() { ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory(); Validator validator = validatorFactory.getValidator(); if (ChannelEnum.IOS.getCode().equals(this.getChannel())) { Set<ConstraintViolation<RechargeConfigDTO>> set = validator.validate(this, IOSConfig.class); if (!CollectionUtils.isEmpty(set)) { for (ConstraintViolation<RechargeConfigDTO> cv : set) { String message = cv.getPropertyPath().toString().concat(cv.getMessage()); throw new JeecgBootExceptionHandler(message); } } } }