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

问题描述

如果有一个带有某些字段的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...

推荐答案

您无法正常进行此操作.

You can't do it normally.

这是我通过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进行验证.所有休眠注释的验证都将在此时开始,您的自定义动态验证(任何注释不支持的验证)也将开始.
  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.

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

08-06 13:09