先添加依赖
- <!-- hibernate校验框架 -->
- <dependency>
- <groupId>org.hibernate</groupId>
- <artifactId>hibernate-validator</artifactId>
- <version>4.3.1.Final</version>
- </dependency>
封装校验方式,当某个规则校验失败时会打印出该字段的message信息
- package com.xd.core.common.utils;
-
- import java.util.Set;
- import javax.validation.ConstraintViolation;
- import javax.validation.Validation;
- import javax.validation.Validator;
- import org.hibernate.validator.HibernateValidator;
-
- import com.xd.core.common.commom.exception.DataCheckException;
-
-
- public class ValidationUtils {
-
- /**
- * 创建校验对象,只要校验出一个未匹配的属性,立即停止校验并且返回空值的属性message,
- *
- */
- private static Validator validator = Validation.byProvider(HibernateValidator.class).configure().failFast(true)
- .buildValidatorFactory().getValidator();
- //创建校验对象 ,校验出全部未匹配的属性,两种创建方式取一种即可,
- //private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
-
- /**
- * 功能描述: <br>
- * 〈注解验证参数〉
- *
- * @param obj
- * @throws DataCheckException
- * @see [相关类/方法](可选)
- * @since [产品/模块版本](可选)
- */
- public static <T> void validate(T obj) throws DataCheckException {
- Set<ConstraintViolation<T>> constraintViolations = validator.validate(obj);
- // 抛出检验异常
- if (constraintViolations.size() > 0) {
- throw new DataCheckException("10000001",
- String.format("参数校验失败:%s", constraintViolations.iterator().next().getMessage()));
- }
- }
- }
校验对象
- package com.xd.base.service.dto;
- import javax.validation.constraints.NotNull;
- import org.hibernate.validator.constraints.NotBlank;
- import com.xd.core.common.base.BaseDto;
- public class PaymentRequestDto {
-
- // 支付方式alipay:支付宝,tenpay:财付通,;qqpay:QQ钱包,wxpay:微信支付
- @NotNull(message = "支付类型不能为空")
- private Integer payType;
-
- // 商品名称
- @NotBlank(message = "商品名称不能为空")
- private String name;
-
- /** 以下忽略get/set方法*/
- }
使用方式
- public String createUcPayUrl(PaymentRequestDto requestDto) throws Exception {
-
- log.info("收到创建uc支付链接请求[{}]", requestDto);
-
- ValidationUtils.validate(requestDto);
- }
写个mian方法测试下
- public static void main(String[] args) {
- try{
- PaymentRequestDto dto = new PaymentRequestDto();
- //只是new了个对象,未传值
- ValidationUtils.validate(dto);
-
- } catch(Exception e){
- e.printStackTrace();
- }
-
- }
运行后控制台打印的信息
详细教程请戳: https://blog.csdn.net/qq_16605855/article/details/80668990