Springboot自定义注解校验

1.添加依赖

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-validation</artifactId>
		</dependency>

2.定义全局异常处理器

@ControllerAdvice
public class GlobalExceptHandler {

    @ResponseBody
    @ExceptionHandler(value = BizException.class)
    public BaseResponse<?> bizException(BizException e) {
        return new BaseResponse<>(e.getErrorCode());
    }

    @ResponseBody
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public BaseResponse<?> methodArgumentNotValidException(MethodArgumentNotValidException e) {
        System.out.println(e.getMessage());
        return new BaseResponse<>(ErrcodeEnum.ERROR);
    }


    @ResponseBody
    @ExceptionHandler(value = ConstraintDeclarationException.class)
    public BaseResponse<?> constraintDeclarationException(ConstraintDeclarationException e) {
        return null;
    }


    @ResponseBody
    @ExceptionHandler(value = NullPointerException.class)
    public BaseResponse<?> nullException(NullPointerException e) {
        return new BaseResponse<>(ErrcodeEnum.NULL_POINT);
    }
    /**
     * 异常处理
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public BaseResponse<?> exceptionHandler(Exception e) {
        if (e instanceof BizException) {
            BizException bizException = (BizException) e;
            return new BaseResponse<>(bizException.getErrorCode());
        } else {
            return new BaseResponse<>(ErrcodeEnum.ERROR);
        }

    }


}

3.使用java原生注解

@NotBlank(message="内容不能为空")

message中可以添加错误信息

抛出的异常为MethodArgumentNotValidException类型,可以自行处理

4.自定义注解

@Documented
@Target({ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = IsPhoneValidator.class)
public @interface IsPhone {
    boolean required() default true;
    String message() default "手机号格式不正确";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

 注解处理类实现javax.validation ConstraintValidator接口

BizException异常继承ConstraintDeclarationException异常类

抛出的异常如果属于ConstraintDeclarationException异常,则会被直接抛出,否则会转为其他异常,无法被异常处理器BizException捕获

5.不在入参时校验

注入javax.validation Validator接口

校验器可以为false,在业务中处理

校验失败后validate这个set会有值,如果校验全成功,set为空

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值