Javax注解约束@ReportAsSingleViolation

Javax annotation constrainst @ReportAsSingleViolation

我使用 Spring 框架和 bean 验证规范(hibernate 实现)。考虑到下面的代码片段,我使用 @ReportAsSingleViolation:

进行了以下观察

此行为描述的是 Bean 验证规范的一部分还是实施问题?

@Target({ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = {})
//@ReportAsSingleViolation
@NotBlank(message = "The input cannot be blank")
@Pattern(regexp = "[0-9A-Z_]+", message = "The input must content only uppercase, numbers and undescore")
@Size(max = 30, message = "The input must be maximal 30")
@Documented
public @interface MyAnnotation{

    String message() default "{com.example.MyAnnotation.message}";

    Class<?>[] groups() default { };

    Class<? extends Payload>[] payload() default { };
}

这正是 @ReportAsSingleViolation 的目的:组合约束并使用统一消息将它们报告为单个约束。

确实是规范定义的行为。

引用规范:

It is possible to ensure that composing annotations do not raise individual error reports. In this scenario, if one or more composing annotations are invalid, the main constraint is automatically considered invalid and the corresponding error report is generated. To mark a constraint as raising a single constraint error report if either the composed or one of the composing constraints fail, use the @ReportAsSingleViolation annotation.

如果您只想要一个违规及其特定错误消息,您可以使用特定于 Hibernate Validator 的快速失败模式,但请注意它不会 return 每个 属性 一个违规,只是第一个因您的 bean 而失败。

有关快速失败模式的更多详细信息,请参见https://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#section-fail-fast