Java 8新特性探究--重复注解(repeating annotations)

什么是重复注解


允许在同一申明类型(类,属性,或方法)的多次使用同一个注解

一个简单的例子


​ java 8之前也有重复使用注解的解决方案,但可读性不是很好,比如下面的代码:


public @interface Authority {
     String role();
}
public @interface Authorities {
    Authority[] value();
}
public class RepeatAnnotationUseOldVersion {    
    @Authorities({@Authority(role="Admin"),@Authority(role="Manager")})
    public void doSomeThing(){
    }
}

由另一个注解来存储重复注解,在使用时候,用存储注解Authorities来扩展重复注解,我们再来看看java 8里面的做法:

@Repeatable(Authorities.class)
public @interface Authority {
     String role();
}
public @interface Authorities {
    Authority[] value();
}
public class RepeatAnnotationUseNewVersion {
    @Authority(role="Admin")
    @Authority(role="Manager")
    public void doSomeThing(){ }
}

不同的地方是,创建重复注解Authority时,加上@Repeatable,指向存储注解Authorities,在使用时候,直接可以重复使用Authority注解。从上面例子看出,java 8里面做法更适合常规的思维,可读性强一点 .

框架中的应用


1、Spring 框架中应用

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Repeatable(PropertySources.class)
public @interface PropertySource {
    ...
}

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface PropertySources {

    PropertySource[] value();

}

2、阿里开源的配置中心 nacos 中应用

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Repeatable(NacosPropertySources.class)
public @interface NacosPropertySource {
    ...
}

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface NacosPropertySources {

    /**
     * Multiple {@link NacosPropertySource @NacosPropertySource}
     *
     * @return {@link NacosPropertySource @NacosPropertySource} array
     */
    NacosPropertySource[] value();
}

你可能感兴趣的:(Java 8新特性探究--重复注解(repeating annotations))