Hibernate Validator自定义校验枚举类型

本文介绍如何创建自定义枚举校验注解,用于验证对象属性值是否属于预定义的枚举集合,包括注解定义、校验器实现及在项目中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文地址,转载请注明出处: https://blog.youkuaiyun.com/qq_34021712/article/details/87895875  ©王赛超

Bean Validation API定义了一整套标准约束注解,例如@NotNull, @Size等等。如果这些内置约束不够,我们可以轻松创建自定义约束。
参考官方文档:
https://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#validator-customconstraints

具体步骤如下:

  1. 创建一个注解
  2. 实现对该注解的解析
  3. 在项目中使用该注解校验参数

有时候在定义接口的时候,我们经常会有一个对象的属性值只能出现在一组常量中的校验需求,例如用户的性别,状态等。那么我们怎么能更好的校验这个参数呢?我们想拥有一个java注解,把它标记在所要校验的字段上,当开启hibernate validator校验时,就可以校验其字段值是否正确。

为了尽可能的通用,上面提到的一组常量值,我们应该是定义一个枚举类,下面我们看代码实现。

代码实现

1.自定义注解
package com.test.validation.config.validation;

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;

@Target({ ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = EnumCheckValidator.class)
public @interface EnumCheck {

    String message() default "";

    Class<?>[] groups() default { };

    Class<? extends Payload>[] payload() default { };

    Class<? extends Enum<?>> enumClass();

    String enumMethod();
}
2.定义一个校验器实现对该注解的解析
package com.test.validation.config.validation;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

/**
 * @author: wangsaichao
 * @date: 2019/2/23
 * @description:
 */
public class EnumCheckValidator implements ConstraintValidator<EnumCheck, String> {

    private Class<? extends Enum<?>> enumClass;
    private String enumMethod;


    @Override
    public void initialize(EnumCheck enumCheck) {
        enumMethod = enumCheck.enumMethod();
        enumClass = enumCheck.enumClass();

    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (value == null) {
            return Boolean.FALSE;
        }

        if (enumClass == null || enumMethod == null) {
            return Boolean.FALSE;
        }

        Class<?> valueClass = value.getClass();

        try {
            Method method = enumClass.getMethod(enumMethod, valueClass);
            if (!Boolean.TYPE.equals(method.getReturnType()) && !Boolean.class.equals(method.getReturnType())) {
                throw new RuntimeException(String.format("%s method return is not boolean type in the %s class", enumMethod, enumClass));
            }

            if(!Modifier.isStatic(method.getModifiers())) {
                throw new RuntimeException(String.format("%s method is not static method in the %s class", enumMethod, enumClass));
            }

            Boolean result = (Boolean)method.invoke(null, value);
            return result == null ? false : result;
        } catch (NoSuchMethodException | SecurityException e) {
            throw new RuntimeException(String.format("This %s(%s) method does not exist in the %s", enumMethod, valueClass, enumClass), e);
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

对于被校验的方法我们要求,它必须是返回值类型为Boolean或boolean,并且必须是一个静态的方法,返回返回值为null时我们认为是校验不通过的,按false逻辑走。

3.定义枚举类
package com.test.validation.base;

/**
 * @author: wangsaichao
 * @date: 2019/2/23
 * @description:
 */
public enum UserStatusEnum {

    /**正常的*/
    NORMAL,
    /**禁用的*/
    DISABLED,
    /**已删除的*/
    DELETED;

    /** 判断参数合法性 */
    public static boolean isValidName(String name) {
        for (UserStatusEnum userStatusEnum : UserStatusEnum.values()) {
            if (userStatusEnum.name().equals(name)) {
                return true;
            }
        }
        return false;
    }
}
4.接受请求参数的Model
public class UserInfo {

    /** 主键 */
    @NotNull(message = "用户id不存在")
    @Range(min = 1,max = Integer.MAX_VALUE,message = "id不正确")
    private Integer id;

    /** 姓名 */
    @NotBlank(message = "用户姓名不能为空")
    private String name;

    /** 身份证号 */
    @Pattern(regexp="^(\\d{18}|\\d{17}(\\d{1}|[X|x]))$",message="身份证格式不正确")
    private String idCardNum;

    /** 年龄 */
    @NotNull(message="用户年龄不能为空")
    @Range(min = 1,max = 150,message = "年龄必须在[1,150]")
    private Integer age;

    /** 家庭住址 */
    @NotBlank(message = "用户地址不能为空")
    private String address;

    /** 状态 */
    @EnumCheck(enumClass = UserStatusEnum.class,enumMethod = "isValidName",message = "状态不正确")
    private String state;
}
5.在项目中使用该注解校验参数
@RequestMapping(value = "/demo8",method = RequestMethod.POST)
@ResponseBody
public void demo8(@RequestBody @Valid UserInfo userInfo){
    System.out.println(userInfo.toString());
}

测试

请求参数:
{"id":"10","name":"张三","idCardNum":"123456789012345678","age":"25","address":"河北邯郸","state":"瞎写的值,无法验证通过"}
结果

在这里插入图片描述

### Java 中校验枚举值的注解方法 在 Java 的 Bean Validation 框架中,默认提供的注解(如 `@NotNull` 或 `@Pattern`)通常不适用于直接验证枚举类型。这是因为框架本身并未提供专门针对枚举类型的内置约束机制[^3]。 #### 自定义注解实现枚举校验 为了满足这一需求,可以通过创建自定义注解并结合相应的验证器类来完成对枚举类型校验。以下是具体实现方式: 1. **定义自定义注解** 创建一个新的注解,例如 `@EnumValue`,并通过元注解指定其作用范围以及关联的验证逻辑。 ```java import javax.validation.Constraint; import javax.validation.Payload; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target({ElementType.FIELD, ElementType.PARAMETER}) @Retention(RetentionPolicy.RUNTIME) @Constraint(validatedBy = EnumValidator.class) // 关联验证器 public @interface EnumValue { String message() default "Invalid enum value"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; // 定义允许的枚举类 Class<? extends Enum<?>> enumClass(); } ``` 2. **编写验证器类** 实现具体的验证逻辑,确保传入的值属于目标枚举类型中的合法成员。 ```java import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; public class EnumValidator implements ConstraintValidator<EnumValue, Object> { private Enum<?>[] values; @Override public void initialize(EnumValue constraintAnnotation) { this.values = constraintAnnotation.enumClass().getEnumConstants(); // 获取所有枚举常量 if (this.values == null || this.values.length == 0) { throw new IllegalArgumentException("The given enum is empty!"); } } @Override public boolean isValid(Object value, ConstraintValidatorContext context) { if (value == null) { // 如果字段可以为空,则返回 true return true; } for (Enum<?> e : values) { if (e.name().equals(value.toString())) { // 验证输入值是否匹配任意枚举名称 return true; } } return false; // 输入值非法 } } ``` 3. **应用自定义注解** 将新定义的注解应用于需要校验的字段上。 ```java public enum CustomerType { INDIVIDUAL, BUSINESS } public class Customer { @EnumValue(enumClass = CustomerType.class, message = "Unsupported customer type") private String customerType; // Getter and Setter methods... } ``` 4. **测试验证功能** 使用 Hibernate Validator 等工具运行验证流程,确认枚举值的有效性。 ```java import org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator; import javax.validation.Validation; import javax.validation.ValidatorFactory; import javax.validation.Validator; import javax.validation.ConstraintViolation; public class MainApp { public static void main(String[] args) { ValidatorFactory factory = Validation.byDefaultProvider() .configure() .messageInterpolator(new ResourceBundleMessageInterpolator()) .buildValidatorFactory(); Validator validator = factory.getValidator(); Customer customer = new Customer(); customer.setCustomerType("INVALID_TYPE"); Set<ConstraintViolation<Customer>> violations = validator.validate(customer); for (ConstraintViolation<Customer> violation : violations) { System.out.println(violation.getMessage()); // 输出: Unsupported customer type } } } ``` 以上代码展示了如何通过自定义注解和验证器实现对枚举类型校验。这种方法不仅灵活而且易于扩展,能够适应多种业务场景的需求[^4]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值