代码之家  ›  专栏  ›  技术社区  ›  nanachimi

Javax annotation constraintst@ReportAsSingleViolation[closed]

  •  -1
  • nanachimi  · 技术社区  · 6 年前

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

    • 只有在以下情况下才返回默认消息: @报告违规

    • 当我移除 @报告违规 注释,一切正常。与违反的约束对应的所有错误消息都将正确返回。

    @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 { };
    }
    
    1 回复  |  直到 6 年前
        1
  •  4
  •   Guillaume Smet    6 年前

    @ReportAsSingleViolation :组合约束并使用统一消息将其报告为单个约束。

    这确实是规范定义的行为。

    可以确保组合注释不会引发单独的错误报告。在这种情况下,如果一个或多个组合注释无效,则主约束将自动视为无效,并生成相应的错误报告。若要在组合约束或其中一个组合约束失败时将约束标记为引发单个约束错误报告,请使用@ReportAsSingleViolation注释。

    如果您只需要一个冲突及其特定的错误消息,您可以使用Hibernate验证器特定的fail fast模式,但是请注意,它不会为每个属性返回一个冲突,只会为bean返回第一个失败的冲突。

    看到了吗 https://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#section-fail-fast 有关fail fast模式的更多详细信息。