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

相关推荐
Voyager_42 小时前
StringRedisTemplate 和 RedisTemplate 的区别是什么?
java·spring boot
小北方城市网2 小时前
SpringBoot 全局异常处理与接口规范实战:打造健壮可维护接口
java·spring boot·redis·后端·python·spring·缓存
Chan163 小时前
【 微服务SpringCloud | 方案设计 】
java·spring boot·微服务·云原生·架构·intellij-idea
hanqunfeng3 小时前
(三十三)Redisson 实战
java·spring boot·后端
计算机毕设指导63 小时前
基于微信小程序的运动场馆服务系统【源码文末联系】
java·spring boot·微信小程序·小程序·tomcat·maven·intellij-idea
小北方城市网4 小时前
SpringBoot 集成 MyBatis-Plus 实战(高效 CRUD 与复杂查询):简化数据库操作
java·数据库·人工智能·spring boot·后端·安全·mybatis
这儿有个昵称4 小时前
互联网大厂Java面试场景:从Spring Boot到微服务架构
java·spring boot·消息队列·微服务架构·大厂面试·数据库优化
hanqunfeng5 小时前
(四十)SpringBoot 集成 Redis
spring boot·redis·后端
小北方城市网6 小时前
SpringBoot 集成 MinIO 实战(对象存储):实现高效文件管理
java·spring boot·redis·分布式·后端·python·缓存
曹轲恒6 小时前
SpringBoot配置文件(1)
java·spring boot·后端