在运行时动态禁用hibernate验证注释? [英] Disabling hibernate validation annotations dynamically at runtime?

查看:104
本文介绍了在运行时动态禁用hibernate验证注释?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能在运行时关闭每个类的某些约束/注释?例如,如果我想在 firstName 字段上打开 @NotNull 检查,那么这可能吗?



这可以使测试看到某个约束是否被正确触发更简单,因为我可以关闭所有其他约束,并检查一个约束。

解决方案


是否有可能在运行时关闭每个类
的某些约束/注释?例如,如果我想在
的firstName字段中打开@NotNull检查,那可能吗?


不是不是。 Bean验证没有定义这样的功能。 Hibernate Validator HV-98 中存在一个开放的问题,它讨论了重新加载元数据的可能性,但即使在那里你也需要重建验证工厂。

您可以通过XML配置覆盖注释,然后在当时使用不同的配置重新创建 Validator(Factory)实例,但这可能不容易管理。


这将使测试查看某个约束是否正确触发
更简单,因为我可以关闭所有其他的
约束,并且只检查一个约束。

如果是关于测试,你可以使用 Validator.validateValue 来验证给定的字段。除此之外,如果您验证整个对象图并返回一组约束违规,则可以迭代它们并检查元数据。元数据中有足够的信息来验证是否执行了特定的约束并且失败。

Is it possible to turn off certain constraints / annotations per class at runtime? For instance if I wanted to turn of a @NotNull check on a firstName field, is that possible?

This would make testing to see whether a certain constraint is triggered correctly simpler, as I could turn off all the other constraints, and just check that one constraint.

解决方案

Is it possible to turn off certain constraints / annotations per class at runtime? For instance if I wanted to turn of a @NotNull check on a firstName field, is that possible?

No it is not. Bean Validation does not define such a feature. There is an open issue in Hibernate Validator HV-98 which discusses the possibility of reloading metadata, but even there you would need to rebuild the validator factory.

You could override annotations via XML configuration and then recreate the Validator(Factory) instance using different configurations at the time, but that's probably not easy to mange.

This would make testing to see whether a certain constraint is triggered correctly simpler, as I could turn off all the other constraints, and just check that one constraint.

If it is about testing, you can use Validator.validateValue to just validate a given field. Other than that, if you validate the whole object graph and get a set of constraint violations back, you can just iterate over them and inspect the metadata. There is enough information in the metadata to verify that a specific constraints was executed and failed.

这篇关于在运行时动态禁用hibernate验证注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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