springboot自定义校验注解

springboot自定义校验注解

1.引入pom

	
      	javax.validation
        validation-api
        2.0.1.Final
    

2.创建注解类

	package com.atguigu.common.valid;

	import javax.validation.Constraint;
	import javax.validation.Payload;
	import java.lang.annotation.*;
	
	/**
	 * @author zhuyuanwei
	 * @version 1.0
	 * @date 2020/10/21 14:29
	 */
	@Documented
	@Constraint(
	        validatedBy = {ListValueConstraintValidator.class}
	)
	@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
	@Retention(RetentionPolicy.RUNTIME)
	public @interface ListValue {
	    String message() default "{com.jihe.common.valid.ListValue.message}";
	
	    Class[] groups() default {};
	
	    Class[] payload() default {};
	
	    int[] vals() default {};
	
	}

3.创建校验器类

	package com.atguigu.common.valid;
	
	import javax.validation.ConstraintValidator;
	import javax.validation.ConstraintValidatorContext;
	import java.util.HashSet;
	import java.util.Set;
	
	/**
	 * @author zhuyuanwei
	 * @version 1.0
	 * @date 2020/10/21 14:36
	 */
	public class ListValueConstraintValidator implements ConstraintValidator {
	
	    Set set=new HashSet();
	
	    public void initialize(ListValue constraintAnnotation) {
	        int[] vals = constraintAnnotation.vals();
	        for (Integer val:vals) {
	            set.add(val);
	        }
	    }
	
	    public boolean isValid(Integer value, ConstraintValidatorContext constraintValidatorContext) {
	        return set.contains(value);
	    }
	}

4.在resource文件夹下创建ValidationMessages.properties

	com.jihe.common.valid.ListValue.message="提交指定的值"

5.使用

	@ListValue(vals = {0,1})
	只能添加0或者1

你可能感兴趣的:(java)