自定义Validation

1,019次阅读
没有评论

共计 1845 个字符,预计需要花费 5 分钟才能阅读完成。

1.前言

后端服务中,接口参数校验必不可少,常见的有如下几种

自定义Validation

但是,特定场景下是不能满足的,于是乎,就有了自定的的校验注解。

2.定义自定义校验注解

本节将演示1种自定义注解

2.1校验参数值必须在指定的整数数组内部

定义校验规则

public abstract class AbstractCommonValidator {
    /**
     * @param context the context about ConstraintValidatorContext
     * @param name    the name under which to bind the expression variable, cannot be {@code null}
     * @param value   the value to be bound to the specified name
     */
    protected final void unwrap(ConstraintValidatorContext context, String name, Object value) {
        context.unwrap(HibernateConstraintValidatorContext.class).addExpressionVariable(name, value);
    }
}
public class NumberArrayValidator extends AbstractCommonValidator implements ConstraintValidator<NumberArray,Integer> {
    private int[] numberArray;

    @Override
    public void initialize(NumberArray constraintAnnotation) {
        numberArray = constraintAnnotation.value();
    }

    @Override
    public boolean isValid(Integer value, ConstraintValidatorContext context) {
        unwrap(context,"numberArray", Arrays.toString(numberArray));
        if (numberArray.length == 0){
            return true;
        }
        if (Objects.isNull(value)){
            return true;
        }
        return IntStream.of(numberArray).anyMatch(v -> v == value);
    }
}

添加自定义校验注解

@Documented
@Constraint(validatedBy = {NumberArrayValidator.class})
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE})
@Retention(RUNTIME)
public @interface NumberArray {

    String message() default "{cloud.mysteriousman.common.validation.constraints.NumberArray.message}";

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

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

    int[] value() default {};
}

创建默认消息解析文件,ValidationMessages.properties,并放置到classpath路径下

cloud.mysteriousman.common.validation.constraints.NumberArray.message = 需要在指定数字数组${numberArray}范围内

3.测试自定义校验注解

使用注解

@NumberArray(value = {1,2,3,4})

尝试请求并传入不在数组内部的数值

自定义Validation

4.小结

本文演示了自定义注解,并依赖Hibernate的自动发现ValidationMessages的特性,实现了自定义校验。注意,如果文件命名不为ValidationMessages,可以为Springboot的默认名messages,或者自定义,但是需要手动实现消息的解析,即{cloud.mysteriousman.common.validation.constraints.NumberArray.message},如果默认消息固定,也就不用考虑解析了。

正文完
 
mysteriousman
版权声明:本站原创文章,由 mysteriousman 2022-04-18发表,共计1845字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)