使用场景
- 接口参数校验
引入依赖
<dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>2.0.1.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.4.1.Final</version> </dependency>
验证类上添加注解
import org.hibernate.validator.constraints.NotBlank; import javax.validation.constraints.Max; import javax.validation.constraints.Min; public class RefundReq extends BaseSignReq { @NotBlank private String tradeOrderId; @Min(value = 100) @Max(value = 999) private Integer bizId; @NotBlank private String refundOrderId; private List<RefundDetail> refundDetails; } public class BaseSignReq { @NotBlank private String caller; @NotBlank private String noise; @NotBlank private String reqId; @NotBlank private String sign; } public class RefundDetail { @Min(1) private Integer channelType; @Min(1) private Long refundAmount; }
工具类
import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import javax.validation.groups.Default; import java.util.HashMap; import java.util.Map; import java.util.Set; public final class ValidationUtil { private ValidationUtil() {/**/} private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); public static <T> ValidationResult validateEntity(T obj) { ValidationResult result = new ValidationResult(); Set<ConstraintViolation<T>> set = validator.validate(obj, Default.class); if (!CollectionUtils.isEmpty(set)) { result.hasErrors = true; Map<String, String> errorMsg = new HashMap<String, String>(); for (ConstraintViolation<T> cv : set) { errorMsg.put(cv.getPropertyPath().toString(), cv.getMessage()); } result.errorMsg = errorMsg; } return result; } @Getter public static class ValidationResult { //校验结果是否有错 private boolean hasErrors; //校验错误信息 private Map<String, String> errorMsg; } }
使用
ValidationUtil.ValidationResult result = ValidationUtil.validateEntity(req); if (result.isHasErrors()) { log.error("[预支付]校验入参,数据有误[{}]", result); return RestResult.<PrePayRsp>builder() .code(ResultCode.PARAM_VALIDATE_FAIL.code).msg(result.getErrorMsg().toString()) .build(); }