Spring Boot编写自定义校验注解

1、编写一个自定义的校验注解,可以参考官方提供的javax.validation.constraints包下的注解

java 复制代码
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.ElementType.TYPE_USE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

@Documented
// 指定使用哪个自定义的校验器进行校验
@Constraint(validatedBy = {ListValueConstraintValidator.class})
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE})
@Retention(RUNTIME)
public @interface ListValue {

    /**
     * JSR303规定必须包含message、groups和payload
     */
    // 国际化消息会自动去classpath下名为ValidationMessages.properties的文件中查找对应的key
    String message() default "{org.hxr.common.validator.constraints.ListValue.message}";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};

    /**
     * 指定可用的范围值
     */
    int[] vals() default {};
}

2、编写一个自定义的校验器

java 复制代码
import org.hxr.common.validator.constraints.ListValue;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.HashSet;
import java.util.Set;

public class ListValueConstraintValidator implements ConstraintValidator<ListValue, Integer> {

    private Set<Integer> set = new HashSet<>();

    /**
     * 初始化
     * @param constraintAnnotation annotation instance for a given constraint declaration
     */
    @Override
    public void initialize(ListValue constraintAnnotation) {
        int[] vals = constraintAnnotation.vals();
        if (vals != null) {
            for (int val : vals) {
                set.add(val);
            }
        }
    }

    /**
     *
     * @param value 需要校验的controller值
     * @param context context in which the constraint is evaluated
     *
     * @return
     */
    @Override
    public boolean isValid(Integer value, ConstraintValidatorContext context) {
        return set.contains(value);
    }
}

3、在自定义注解中关联自定义校验器,见1@Constraint

相关推荐
MiniFlyZt26 分钟前
消息队列MQ(RabbitMQ)
spring boot·分布式·微服务·rabbitmq
A-Kamen31 分钟前
Spring Boot拦截器(Interceptor)与过滤器(Filter)深度解析:区别、实现与实战指南
java·spring boot·后端
trymoLiu44 分钟前
SpringBoot 实现 RSA+AES 自动接口解密!
java·spring boot
wolf犭良2 小时前
26、《Spring Boot OpenFeign:声明式服务调用与熔断降级深度实践》
java·spring boot·后端
@卡卡-罗特2 小时前
Spring Boot笔记(上)
spring boot·笔记·后端
卡布奇诺-海晨3 小时前
JVM之Arthas的dashboard命令以及CPU飙高场景
java·spring boot
katasea3 小时前
关于Springboot 应配置外移和Maven个性化打包一些做法
spring boot·maven
Huooya4 小时前
springboot的外部配置加载顺序
spring boot·面试·架构
钢板兽4 小时前
Java后端高频面经——Spring、SpringBoot、MyBatis
java·开发语言·spring boot·spring·面试·mybatis
用户53866168248225 小时前
SpringBoot 业务中 通过嵌套异步的方式 提高业务表数据同步效率
java·spring boot