如何在运行时更改注释/休眠验证规则? [英] How can I change annotations/Hibernate validation rules at runtime?

查看:31
本文介绍了如何在运行时更改注释/休眠验证规则?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果有一个包含某些字段的 Java 类,我想使用 Hibernate Validator 进行验证.现在,我希望我的用户能够在运行时配置进行哪些验证.

If have a Java class with some fields I want to validate using Hibernate Validator. Now I want my users to be able to configure at runtime which validations take place.

例如:

public class MyPojo {
    ...

    @NotEmpty
    String void getMyField() {
        ... 
    }

    ...
}

假设我想删除 NotEmpty 检查或替换为 EmailCreditCardNumber,我该怎么做?甚至有可能吗?我想这归结为在运行时更改注释...

Let's say I want to remove the NotEmpty check or replace it with Email or CreditCardNumber, how can I do it? Is it even possible? I guess it comes down to changing annotations at runtime...

推荐答案

不能正常操作.

以下是我为通过 Hibernate Validator 获得更多动态验证所做的工作.

Here's what I've done to get more dynamic validations working via Hibernate Validator.

  1. 扩展 ClassValidator 类.
  2. 覆盖 getInvalidVaues(Object myObj) 方法.首先,调用 super.getInvalidValues(myObj),然后将钩子添加到您的自定义验证中.
  3. 实例化您的自定义验证器并调用 getInvalidValues 进行验证.此时,所有带 Hibernate 注释的验证都将启动,您的自定义动态验证(注释不支持的任何验证)也将启动.
  1. Extend the ClassValidator class.
  2. Override the getInvalidVaues(Object myObj) method. First, call super.getInvalidValues(myObj), then add the hook to your customized validation.
  3. Instantiate your custom validator and call getInvalidValues to validate. Any hibernate annotated validations will kick off at this point, and your custom dynamic validations (anything not supported by annotations) will kick off as well.

示例:

public class MyObjectValidator extends ClassValidator<MyObject>
{
    public MyObjectValidator()
    {
         super(MyObject.class);
    }

    public InvalidValue[] getInvalidValues(MyObject myObj)
    {
        List<InvalidValue> invalids = new ArrayList<InvalidValue>();
        invalids.addAll(Arrays.asList(super.getInvalidValues(myObj)));

        // add custom validations here
        invalids.addAll(validateDynamicStuff(myObj));

        InvalidValue[] results = new InvalidValue[invalids.size()];
        return invalids.toArray(results);
    }

    private List<InvalidValue> validateDynamicStuff(MyObject myObj)
    {
        // ... whatever validations you want ...
    }

}

因此,您的自定义验证代码可以包含诸如执行此验证,如果用户配置它,否则执行此验证"等逻辑.您可能能够也可能无法利用支持休眠验证的相同代码,但是无论哪种方式,您所做的都比休眠验证器的正常"用例更复杂.

So your custom validation code can contain logic like "Do this validation, if the user configured it, otherwise do that one", etc. You may or may not be able to leverage the same code that powers the hibernate validations, but either way, what you are doing is more involved that the 'normal' use case for hibernate validator.

这篇关于如何在运行时更改注释/休眠验证规则?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆