JDK8中新增加注解Repeatable ,今天在看《SpringBoot编程思想》中走向注解驱动编程(Annatation-Driven)这一章节中提到了这个注解,我对这个注解感到比较陌生,以前读springboot源码也看到了这个注解,现在就学习可以一下。
Repeatable 源代码
package java.lang.annotation;
/**
* The annotation type {@code java.lang.annotation.Repeatable} is
* used to indicate that the annotation type whose declaration it
* (meta-)annotates is <em>repeatable</em>. The value of
* {@code @Repeatable} indicates the <em>containing annotation
* type</em> for the repeatable annotation type.
*
* @since 1.8
* @jls 9.6.3 Repeatable Annotation Types
* @jls 9.7.5 Multiple Annotations of the Same Type
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Repeatable {
/**
* Indicates the <em>containing annotation type</em> for the
* repeatable annotation type.
* @return the containing annotation type
*/
Class<? extends Annotation> value();
}
The annotation type java.lang.annotation.Repeatable is used to indicate that
the annotation type whose declaration it (meta-)annotates is repeatable.
The value of @Repeatable
indicates the containing annotation type for the repeatable annotation type.
@Repeatable 注解用于指示它注解声明的注解类型是可重复的。
@Repeatable 的值用于指示一个注解类型,这个注解类型用来存放可重复的注解类型。
我们先定义一个角色注解Role,这个注解用@Repeatable声明,表示可以重复在一个类上使用@Role,而多个@Role存放在@Roles注解的value中。
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Repeatable(Roles.class)
public @interface Role {
String value() default "";
}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Roles {
Role[] value();
}
创建两个用户类,并且使用Role注解标注
@Role("custom")
@Role("biz_admin")
public class BizUser {
private String name;
}
@Role("custom")
@Role("system_admin")
public class SysUser {
private String name;
}
测试Demo如下
public class RepeatableDemo {
public static void main(String[] args) {
if(SysUser.class.isAnnotationPresent(Roles.class)) {
Roles roles = SysUser.class.getAnnotation(Roles.class);
System.out.println("SysUser的角色如下:");
for(Role role : roles.value())
System.out.println(role.value());
}
if(BizUser.class.isAnnotationPresent(Roles.class)) {
Roles roles = BizUser.class.getAnnotation(Roles.class);
System.out.println("BizUser的角色如下:");
for(Role role : roles.value())
System.out.println(role.value());
}
}
}
@Role与@Roles的配合,Java8+如下
@Role("custom")
@Role("system_admin")
public class SysUser {
private String name;
}
Java8之前的等效写法如下
@Roles({
@Role("custom"),
@Role("system_admin")
})
public class SysUser {
private String name;
}