java 8支持同一个属性多次使用相同注解

背景

  • 一般情况下同一个注解在一个属性上使用,编译都过不了,如下图所示。
    在这里插入图片描述

解决方案

  • 新建一个注解
import java.lang.annotation.*;

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Annotations {
    ConditionalValidateField[] value();
}
  • 引用刚才的注解

@Repeatable(Annotations.class)
public @interface ConditionalValidateField {
...省略...
}
  • 这样子就不报错了
    在这里插入图片描述
  • 这个属性用反射会得到多个注解,也可以直接用Spring的方法AnnotationUtils.getRepeatableAnnotations(注意5.2版本是过时的)

posted on 2022-03-24 18:01  愤怒的苹果ext  阅读(60)  评论(0编辑  收藏  举报

导航