在运行时动态禁用休眠验证注释?

Disabling hibernate validation annotations dynamically at runtime?

是否可以在运行时根据 class 关闭某些约束/注释?例如,如果我想在 firstName 字段上关闭 @NotNull 检查,这可能吗?

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

hibernate 验证注释通常与数据库约束一起使用,因此在运行时更改行为没有意义。然而,如果你想这样做,你可以实现你自己的验证器(通过覆盖现有的)并做任何你想做的事。

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?

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

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

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.

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