这个嵌套注解是做什么/允许什么?

11

我正在查看@org.hibernate.validator.constraints.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即可。 - Amir Pashazadeh
现在,您可以使用@Repeatable和容器注释来实现相同的目标,从而减少注释和被注释对象中的冗长代码。 - Ghoti and Chips
1个回答

12

NotEmpty.List的存在是为了绕过不能在同一元素上重复使用相同注释的限制。通过NotEmpty.List的帮助,可以将多个NotEmpty注释有效地应用于一个元素。注释处理会检查NotEmpty.List的值列表中的所有NotEmpty注释。

对于NotEmpty而言,使用验证器列表的原因之一可能是使用并针对每个组分配不同的消息。

为了举例说明,让我们考虑一个既可以代表公司又可以代表个人的实体。在两种情况下,名称都不应该为null,但是消息不同:

@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({ ... })吧? - Eric B.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接