springboot的Validator的帮助类

springboot的Validator的帮助类

ValidatorUtils

public class ValidatorUtils {
    private static Validator validator;

    static {
        validator = Validation.byDefaultProvider().configure().messageInterpolator(
            new ResourceBundleMessageInterpolator(new MessageSourceResourceBundleLocator(getMessageSource())))
            .buildValidatorFactory().getValidator();
    }

    private static ResourceBundleMessageSource getMessageSource() {
        ResourceBundleMessageSource bundleMessageSource = new ResourceBundleMessageSource();
        bundleMessageSource.setDefaultEncoding("UTF-8");
        bundleMessageSource.setBasenames("i18n/validation");
        return bundleMessageSource;
    }

    /**
     * 校验对象
     * @param object        待校验对象
     * @param groups        待校验的组
     */
    public static void validateEntity(Object object, Class<?>... groups)
            throws BusinessException {
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        if (!constraintViolations.isEmpty()) {
        	ConstraintViolation<Object> constraint = constraintViolations.iterator().next();
            throw new BusinessException(constraint.getMessage());
        }
    }
}

Exception

public class BusinessException extends RuntimeException {

    private String errorCode;

    public BusinessException() {
    }

    public BusinessException(String message) {
        super(message);
    }
    
    public BusinessException(String errorCode, String message) {
        super(message);
        this.errorCode = errorCode;
    }

    public BusinessException(String message, Throwable cause) {
        super(message, cause);
    }
    
    public BusinessException(String errorCode, String message, Throwable cause) {
        super(message, cause);
        this.errorCode = errorCode;
    }

    public BusinessException(Throwable cause) {
        super(cause);
    }

    public BusinessException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }

    public String getErrorCode() {
        return errorCode;
    }

    public void setErrorCode(String errorCode) {
        this.errorCode = errorCode;
    }

}

使用

    @GetMapping("/getSysUserListByPage")
    @ResponseBody
    @ApiOperation(value = "查询系统用户数据并分页")
    public ResponseModel getSysUserListByPage(SysUserTabReq req) {
    	 ValidatorUtils.validateEntity(req);
        PageInfo<SysUserTabResp> pageInfo = apiUserService.getSysUserListByPage(req);
        return ResponseModel.success(pageInfo);
    }

全局异常处理BusinessException

 @ExceptionHandler(value = BusinessException.class)
    public ResponseModel exceptionHandler(BusinessException e) {
        return ResponseModel.fail(e.getMessage());
    }

你可能感兴趣的:(springboot的Validator的帮助类)