@AliasFor注解

2022-07-27  本文已影响0人  engineer_tang

注解定义如下:

@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 使用场景:

2.2 实现上

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

2.3 实施要求

注解中的显示别名:

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

注释中的隐式别名:

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 {};
   }
上一篇 下一篇

猜你喜欢

热点阅读