配置注解进行参数校验(配合全局异常)

在编写业务代码时无可避免的进行参数校验,如 if (null != xxx) { … }
这样判断非空代码无可避免地不太优雅

此时如果可以在字段上添加注解即可进行非空校验的报错,代码就显得很简单,优雅。

使用springboot的validation组件即可实现。

首先在pom.xml中声明validation组件:

<!-- md5 -->
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
        </dependency>
        <!-- validation组件 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>

然后在对应需要操作的实体类字段上声明@NotNull,测试即可发现只在控制台报错,而不能返回错误信息。此时应想到创建全局异常进行捕获操作。
但除了异常信息无法返回的问题,还会发现该组件自己提供的参数校验很少,常用的比如电话号码校验缺失。此时可自定义注解及配置方法进行操作。

自定义注解:
按住ctrl键点击@NotNull注解,比葫芦画瓢即可:

@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = {IsMobileValidator.class})
public @interface IsMobile {

    boolean required() default true;

    String message() default "手机号码格式错误";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

针对该自定义注解进行校验规则的配置:

//                                                           注解本解   要验证的数据类型
public class IsMobileValidator implements ConstraintValidator<IsMobile,String> {

    private boolean required = false;

    //初始化注解
    @Override
    public void initialize(IsMobile constraintAnnotation) {
        //注解被初始化后将required赋值为true
        //注解required是否为必填
        required = constraintAnnotation.required();
    }

    @Override
    public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
        //注解required是必填
        if (required) {
            return ValidatorUtil.isMobile(s);
        } else {
        //注解required不是必填
            //被注解的值是否为空
            if (StringUtils.isBlank(s)) {
                return true;
            } else {
                return ValidatorUtil.isMobile(s);
            }
        }
    }
}

最后再对抛出的异常进行处理(全局异常处理):
经过测试后可发现注解抛出的异常是BindException;

public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public RespBean exceptionHandler(Exception e) {
        if (e instanceof GlobalException) {
            GlobalException globalException = (GlobalException) e;
            return RespBean.error(RespBeanEnum.LOGINERROR);
        } else if (e instanceof BindException) {
            BindException bindException = (BindException) e;
            RespBean respBean = RespBean.error(RespBeanEnum.BINDERROR);
            respBean.setMsg("参数校验异常:"+bindException.getBindingResult().getAllErrors().get(0).getDefaultMessage());
            return respBean;
        }
        return RespBean.error(RespBeanEnum.ERROR);
    }
}

项目:seckill

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值