Hibernate Validator @NotNull 总是先触发吗?

Is Hibernate Validator @NotNull always triggered first?

换句话说,如果我有两个约束,例如 @Email@NotNull@Email 验证器不会抛出 NPE?

这似乎很明显,但我问是因为我看到一些自定义验证器会检查要验证的值是否为空,如果是 return 则为真。这似乎是个坏主意,因为如果开发人员忘记将 @NotNull 添加到 email 字段,那么电子邮件字段仍将通过验证。

TIA, 奥莱

null 返回 true 被认为是 Bean 中的最佳实践 验证和所有内置约束都遵守它(如果可能)。 Bean 验证规范在 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.