赞
踩
1,引入核心关键依赖
- <!--数据校验-->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-validation</artifactId>
- </dependency>
2,自定义注解
- package com.taia.yms.aop.validate;
-
- import javax.validation.Constraint;
- import javax.validation.Payload;
- import java.lang.annotation.*;
-
- @Target({ElementType.FIELD, ElementType.TYPE})
- @Retention(RetentionPolicy.RUNTIME)
- @Documented
- @Constraint(validatedBy = {IntegerMinValidator.class}) // 标明由哪个类执行校验逻辑
- /**
- * 校验字段为整数 且 大于某个值场景
- */
- public @interface IntegerMin {
-
- String message() default "{com.taia.yms.aop.validate.IntegerMin.message}";
- Class<?>[] groups() default { };
-
- Class<? extends Payload>[] payload() default { };
-
- int value() default 0;
- }
3,定义核心校验类
- package com.taia.yms.aop.validate;
-
- import lombok.extern.slf4j.Slf4j;
-
- import javax.validation.ConstraintValidator;
- import javax.validation.ConstraintValidatorContext;
- import java.util.regex.Pattern;
-
- @Slf4j
- public class IntegerMinValidator implements ConstraintValidator<IntegerMin, Object> {
- private int minValue;
- // 匹配整数(包括正数和负数)
- private static final Pattern pattern = Pattern.compile("-?\\d+");
- @Override
- public void initialize(IntegerMin constraintAnnotation) {
- minValue = constraintAnnotation.value();
- }
-
- @Override
- public boolean isValid(Object object, ConstraintValidatorContext context) {
- try{
- String str = object == null ? "0" :String.valueOf(object);
- if(!pattern.matcher(str).matches()){
- log.warn("IntegerMinValidator->isValid value is not Integer!");
- return false;
- }
- int value = Integer.valueOf(str);
- return value >= minValue;
- }catch (Exception e){
- log.warn("IntegerMinValidator->isValid error,message:{}",e.getMessage());
- return false;
- }
- }
- }
4,使用
- @IntegerMin(value = -1,message = "adderRetrieveLayer 值范围为-1或大于0的整数")
- private Integer adderRetrieveLayer;
参照:
SpringBoot Validation参数校验 详解自定义注解规则和分组校验_spring valid 自定义注解 不同条件-CSDN博客
SpringBoot自定义validation注解校验参数只能为指定的值_springboot项目 validation 怎么限制参数只能是 -1和1-CSDN博客
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。