Spring Validator 数据校验

在SpringBoot中工程中通常需要对数据作校验,而有些时候前端传入的参数只能是特定值。可以考虑定义一个枚举类

工程

pom

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.3.5.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

 <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-web</artifactId>
 </dependency>
 <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-validation</artifactId>
 </dependency>

校验定义

@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = ForEnumValidator.class)
public @interface ForEnum {
    /**
     * @return 提示内容
     */
    String message() default "必须在指定范围 {value}";

    /**
     * 枚举类
     */
    Class<? extends Enum<?>> enumClass();

    /**
     * 获取指定的方法名。此方法必须是无参方法
     */
    String methodName() default "name";

    /**
     * @return 分组
     */
    Class<?>[] groups() default {};

    /**
     * @return Payload 数组
     */
    Class<? extends Payload>[] payload() default {};

    @Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @interface List {
        ForEnum[] value();
    }
}
// 这里将泛型定义为Object,可以对任意数据类型作校验
public class ForEnumValidator implements ConstraintValidator<ForEnum, Object> {
    // 枚举类型
    private Class<? extends Enum<?>> enumClass;
    // 获取值方法
    private String methodName;

    @Override
    public void initialize(ForEnum annotation) {
        enumClass = annotation.enumClass();
        methodName = annotation.methodName();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        Method method = ReflectionUtils.findMethod(enumClass, methodName);
        return Arrays.stream(enumClass.getEnumConstants())
                .map(item -> ReflectionUtils.invokeMethod(method, item))
                .anyMatch(item -> item.equals(value));
    }
}

测试

// 取值限定枚举类
public enum Color {
    RED("红色", "red", 1),
    GREEN("绿色", "green", 2),
    BLANK("白色", "blank", 3),
    YELLO("黄色", "yello", 4);
    // 成员变量
    private String name;
    private int index;
    private String title;

    // 构造方法
    Color(String name, String title, int index) {
        this.name = name;
        this.title = title;
        this.index = index;
    }
}
public class Person {
    @ForEnum(enumClass = Color.class, methodName = "getTitle")
    private String color;
    @ForEnum(enumClass = Color.class, methodName = "getIndex")
    private Integer age;
}
@RestController
public class DemoController {
    @PostMapping("demo")
    public Person person(@RequestBody @Valid Person person) {
        return person;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

①笶侕濄

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值