【问题标题】:What does this nested annotation do / allow?这个嵌套注释做什么/允许什么?
【发布时间】:2014-07-22 20:59:43
【问题描述】:

我在看@org.hibernate.validator.constaints.NotEmpty注解:

@Documented
@Constraint(validatedBy = { })
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@ReportAsSingleViolation
@NotNull
@Size(min = 1)
public @interface NotEmpty {
    String message() default "{org.hibernate.validator.constraints.NotEmpty.message}";

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

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

    /**
     * Defines several {@code @NotEmpty} annotations on the same element.
     */
    @Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
    @Retention(RUNTIME)
    @Documented
    public @interface List {
        NotEmpty[] value();
    }
}

我对最后一部分感到困惑:

    /**
     * Defines several {@code @NotEmpty} annotations on the same element.
     */
    @Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
    @Retention(RUNTIME)
    @Documented
    public @interface List {
        NotEmpty[] value();
    }

我不确定它是如何工作的,也不知道如何使用它。据我了解,Java 8 下的任何内容都不允许在同一元素上重复注释。

谁能澄清一下?

【问题讨论】:

  • 它就像一个嵌套的静态类或嵌套接口。 @NotEmpty.List 使用它。
  • 现在,您可以使用@Repeatable 和容器注释来实现相同的目标,同时在注释和您要注释的内容中使用更少的冗长代码

标签: java hibernate validation annotations spring-validator


【解决方案1】:

NotEmpty.List 存在的原因是为了解决不能为同一元素重复相同注释的事实。在 NotEmpty.List 的帮助下,多个NotEmpty 注释有效地应用于一个元素。注释处理检查作为 NotEmpty.List 值的 NotEmpty 注释列表。

在 NotEmpty 的情况下,使用验证器列表的一个原因可能是使用 groups 并为每个组分配不同的消息。

为了举例,让我们以可以代表公司或个人的实体为例。在这两种情况下,名称都不应为空,但消息不同:

@NotEmpty.List({
    @NotEmpty( message = "Person name should not be empty",   
               groups=PersonValidations.class),
    @NotEmpty( message = "Company name should not be empty",    
               groups=CompanyValidations.class),
})
private String name;

【讨论】:

  • 那一定是@NotEmpty.List({ ... }) 不是吗?
猜你喜欢
  • 1970-01-01
  • 2011-08-17
  • 2011-10-14
  • 2013-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-19
相关资源
最近更新 更多