美文网首页
@AliasFor注解

@AliasFor注解

作者: engineer_tang | 来源:发表于2022-07-27 10:30 被阅读0次

注解定义如下:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface AliasFor {

    @AliasFor("attribute")
    String value() default "";

    @AliasFor("value")
    String attribute() default "";

    Class<? extends Annotation> annotation() default Annotation.class;

}

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 是彼此的显式别名。

 public @interface ContextConfiguration {
  
      @AliasFor("locations")
      String[] value() default {};
  
      @AliasFor("value")
      String[] locations() default {};
  
      // ...
   }

示例2:元注释中属性的显式别名
在@XmlTestConfig中,xmlFiles是@ContextConfiguration中位置的显式别名。换句话说,xmlFiles覆盖@ContextConfiguration中的locations属性。

 @ContextConfiguration
   public @interface XmlTestConfig {
  
      @AliasFor(annotation = ContextConfiguration.class, attribute = "locations")
      String[] xmlFiles();
   }

示例3:注释中的隐式别名
在@MyTestConfig中,value、groovyscript和xmlFiles都是@ContextConfiguration中locations属性的显式元注释属性重写。因此,这三个属性也是彼此的隐式别名。

 @ContextConfiguration
   public @interface MyTestConfig {
  
      @AliasFor(annotation = ContextConfiguration.class, attribute = "locations")
      String[] value() default {};
  
      @AliasFor(annotation = ContextConfiguration.class, attribute = "locations")
      String[] groovyScripts() default {};
  
      @AliasFor(annotation = ContextConfiguration.class, attribute = "locations")
      String[] xmlFiles() default {};
   }

相关文章

网友评论

      本文标题:@AliasFor注解

      本文链接:https://www.haomeiwen.com/subject/angtwrtx.html