一、前言
因为我想对于参数的校验制定自己的规则,所以要自定义一个校验器。
好的,开始启动吧
二、元神启动!
1. springboot项目引入相关依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-validation</artifactId></dependency>
2. 创建student类
@Data
@AllArgsConstructor
@NoArgsConstructorpublic class Student {@PositiveInteger(message = "年龄必须是正整数")Number age;String name;String gender;
}
@RestController
public class ValidController {@PostMapping("/valid")public Number valid(@Valid @RequestBody Student student) {return student.getAge();}}
3. 创建PositiveInteger接口
import jakarta.validation.Constraint;
import jakarta.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = PositiveIntegerValidator.class)
public @interface PositiveInteger {String message() default "Must be a positive integer";Class<?>[] groups() default {};Class<? extends Payload>[] payload() default {};int min() default 1; // 整数的最小值// 定义嵌套注解,用于支持重复注解(用处不大,不写也行)@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface List {PositiveInteger[] value(); // 用于存储多个@Null注解实例}
}
@Constraint(validatedBy = PositiveIntegerValidator.class)
是Java Bean Validation框架中的一个元注解,它用来指定哪个验证器类(validator class)应该负责处理当前注解的验证逻辑。
在这个例子中,@PositiveInteger
是一个自定义的注解,用于标记某个字段必须为正整数。@Constraint
注解告诉验证框架,当遇到 @PositiveInteger
注解时,应该使用 PositiveIntegerValidator
类来进行实际的验证操作。
4. 创建校验类
public class PositiveIntegerValidator implements ConstraintValidator<PositiveInteger, Number> {private Integer min;@Overridepublic void initialize(PositiveInteger constraintAnnotation) {min=constraintAnnotation.min();}@Overridepublic boolean isValid(Number number, ConstraintValidatorContext constraintValidatorContext) {if (number != null && number instanceof Integer && (Integer)number>min) {return true;}return false;}}