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+");@Overridepublic void initialize(IntegerMin constraintAnnotation) {minValue = constraintAnnotation.value();}@Overridepublic 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博客
?