5.@AliasFor注解

注解定义如下:

 1 @Retention(RetentionPolicy.RUNTIME)
 2 @Target(ElementType.METHOD)
 3 @Documented
 4 public @interface AliasFor {
 5 
 6     @AliasFor("attribute")
 7     String value() default "";
 8 
 9     @AliasFor("value")
10     String attribute() default "";
11 
12     Class<? extends Annotation> annotation() default Annotation.class;
13 
14 }

1. 属性说明

1.1 annotation属性

声明别名属性的注释类型。
默认为注释,这意味着别名属性在与此属性相同的注释中声明。

1.2. attribute属性

此属性是其别名的属性的名称。

1.3. value属性

用于在未声明注释时代替属性-例如:@AliasFor(“value”)而不是@AliasFor(attribute=“value”)。

2. 注解用法

2.1 使用场景:

  • 在注解中一对属性上通过声明@AliasFor,进行属性互换。
  • 在注解上声明了另一个注解,对另一个注解的属性进行别名覆盖。
  • 隐式别名

2.2 实现上

通过MergedAnnotations加载@AliasFor注解实现别名功能。

2.3 实施要求

注解中的显示别名:

  • 构成别名对的每个属性都应该用@AliasFor注释,并且属性或值必须引用该对中的另一个属性。由于Spring Framework 5.2.1,从技术上讲,可以只注释别名对中的一个属性;但是,建议在别名对中对这两个属性进行注释,以获得更好的文档以及与Spring Framework早期版本的兼容性。
  • 别名属性必须声明相同的返回类型。
  • 别名属性必须声明默认值。
  • 别名属性必须声明相同的默认值。
  • 不应声明注释。

元注释中属性的显式别名:

  • 作为元注释中属性别名的属性必须用@AliasFor注释,并且属性必须引用元注释中的属性。
  • 别名属性必须声明相同的返回类型。
  • 注释必须引用元注释。
  • 引用的元注释必须在声明@AliasFor的注释类上存在。

注释中的隐式别名:

  • 属于一组隐式别名的每个属性都必须用@AliasFor注释,并且属性必须在同一元注释中引用同一属性(直接或通过注释层次结构中的其他显式元注释属性覆盖传递)。
  • 别名属性必须声明相同的返回类型。
  • 别名属性必须声明默认值。
  • 别名属性必须声明相同的默认值。
  • 注释必须引用适当的元注释。
  • 引用的元注释必须在声明@AliasFor的注释类上存在。

3. 实例

示例1:注释中的显式别名,在@ContextConfiguration中,value 和locations 是彼此的显式别名。

 1  public @interface ContextConfiguration {
 2   
 3       @AliasFor("locations")
 4       String[] value() default {};
 5   
 6       @AliasFor("value")
 7       String[] locations() default {};
 8   
 9       // ...
10    }
示例2:元注释中属性的显式别名
在@XmlTestConfig中,xmlFiles是@ContextConfiguration中位置的显式别名。换句话说,xmlFiles覆盖@ContextConfiguration中的locations属性。
1  @ContextConfiguration
2    public @interface XmlTestConfig {
3   
4       @AliasFor(annotation = ContextConfiguration.class, attribute = "locations")
5       String[] xmlFiles();
6    }
示例3:注释中的隐式别名
在@MyTestConfig中,value、groovyscript和xmlFiles都是@ContextConfiguration中locations属性的显式元注释属性重写。因此,这三个属性也是彼此的隐式别名。
 1  @ContextConfiguration
 2    public @interface MyTestConfig {
 3   
 4       @AliasFor(annotation = ContextConfiguration.class, attribute = "locations")
 5       String[] value() default {};
 6   
 7       @AliasFor(annotation = ContextConfiguration.class, attribute = "locations")
 8       String[] groovyScripts() default {};
 9   
10       @AliasFor(annotation = ContextConfiguration.class, attribute = "locations")
11       String[] xmlFiles() default {};
12    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值