换句话说,如果我有两个约束,例如 @Email
和 @NotNull
,@Email
validator 不会抛出 NPE?
这似乎很明显,但我之所以这么问,是因为我看到一些自定义 validator 检查要验证的值是否为空,如果是则返回 true。这似乎是一个坏主意,因为如果开发人员忘记将 @NotNull
添加到 email
字段,那么电子邮件字段仍将通过验证。
TIA, 奥莱
最佳答案
为 null
返回 true
被认为是 Bean 中的最佳实践
验证和所有内置约束都遵守它(如果可能)。
Bean Validation 规范在 3.4. Constraint validation implementation 部分中有说明。 :
While not mandatory, it is considered a good practice to split the core constraint validation from the not null constraint validation (for example, an @Email constraint will return true on a null object, i.e. will not take care of the @NotNull validation).
null can have multiple meanings but is commonly used to express that a value does not make sense, is not available or is simply unknown. Those constraints on the value are orthogonal in most cases to other constraints. For example a String, if present, must be an email but can be null. Separating both concerns is a good practice.
关于java - Hibernate Validator @NotNull 总是首先触发吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38130333/