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

相关推荐
这是程序猿13 分钟前
基于java的ssm框架旅游在线平台
java·开发语言·spring boot·spring·旅游·旅游在线平台
i***t91932 分钟前
基于SpringBoot和PostGIS的云南与缅甸的千里边境线实战
java·spring boot·spring
k***082933 分钟前
【监控】spring actuator源码速读
java·spring boot·spring
一 乐1 小时前
应急知识学习|基于springboot+vue的应急知识学习系统(源码+数据库+文档)
数据库·vue.js·spring boot
vx_dmxq2111 小时前
【PHP考研互助系统】(免费领源码+演示录像)|可做计算机毕设Java、Python、PHP、小程序APP、C#、爬虫大数据、单片机、文案
java·spring boot·mysql·考研·微信小程序·小程序·php
5***g2981 小时前
新手如何快速搭建一个Springboot项目
java·spring boot·后端
vx_vxbs663 小时前
【SSM电影网站】(免费领源码+演示录像)|可做计算机毕设Java、Python、PHP、小程序APP、C#、爬虫大数据、单片机、文案
java·spring boot·python·mysql·小程序·php·idea
AI分享猿4 小时前
Java后端实战:SpringBoot接口遇异常请求,轻量WAF兼顾安全与性能
java·spring boot·安全
q***69775 小时前
【Spring Boot】统一数据返回
java·spring boot·后端
v***59835 小时前
DeepSeek API 调用 - Spring Boot 实现
windows·spring boot·后端