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

相关推荐
{{uname}}7 小时前
利用WebSocket实现实时通知
网络·spring boot·websocket·网络协议
goTsHgo8 小时前
Spring Boot 自动装配原理详解
java·spring boot
唐僧洗头爱飘柔95279 小时前
【SSM-SSM整合】将Spring、SpringMVC、Mybatis三者进行整合;本文阐述了几个核心原理知识点,附带对应的源码以及描述解析
java·spring·mybatis·springmvc·动态代理·ioc容器·视图控制器
秋野酱12 小时前
基于javaweb的SpringBoot爱游旅行平台设计和实现(源码+文档+部署讲解)
java·spring boot·后端
qq_124987075312 小时前
原生小程序+springboot+vue医院医患纠纷管理系统的设计与开发(程序+论文+讲解+安装+售后)
java·数据库·spring boot·后端·小程序·毕业设计
伊成12 小时前
一文详解Spring Boot如何配置日志
java·spring boot·单元测试
bing_15813 小时前
Spring Boot 的自动配置为 Spring MVC 做了哪些事情?
spring boot·spring·mvc
嘵奇15 小时前
Spring Boot中HTTP连接池的配置与优化实践
spring boot·后端·http
Persistence___17 小时前
SpringBoot中的拦截器
java·spring boot·后端
嘵奇17 小时前
Spring Boot 跨域问题全解:原理、解决方案与最佳实践
java·spring boot·后端