springboot自定义校验注解

it2024-08-13  35

springboot自定义校验注解

1.引入pom

<dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>2.0.1.Final</version> </dependency>

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<? extends Payload>[] 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<ListValue,Integer> { Set<Integer> set=new HashSet<Integer>(); 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
最新回复(0)