AliasFor注解-1

一、AliasFor注解

  @AliasFor注解用于声明注解属性的别名,常用于组合注解。

二、使用场景

  1)在一个注解中显示为属性设置别名

  如下1.1定义一个ContextConfiguration注解,该注解含有value和locations两个属性,分别为value设置别名locations,locations设置别名value。在使用@ContextConfiguration注解时无论是为value设置值,还是为locations设置值达到的效果相同。

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

  使用限制:

  • 别名都是成对出现,为value属性设置locations别名,需要含有locations属性并为其设置value别名;
  • 成对出现的属性返回值相同;
  • 必须为成对出现的属性必须设置默认值;
  • 成对出现的属性的默认值必须相同;
  • AliasFor注解不能设置annotation属性;

  2)为元注解设置别名属性

  如下1.2定义@XmlTestConfig注解并使用1.2中定义的@ContextConfiguration注解进行修饰。其中,xmlFiles属性使用@AliasFor注解修饰,@AliasFor注解的annotation属性是ContextConfiguration,attribute属性是locations表示当使用@XmlTestConfig注解并设置xmlFiles属性时等同于设置了@ContextConfiguration中的locations属性。

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

  使用限制:

  • AliasFor中定义的annotation属性必须为该注解元注解;
  • AliasFor中定义的attribute属性的值必须为annotation属性指定的元注解中的属性;

  3)一个注解中的隐式别名

  如下1.3中定义了一个@MyTestConfig注解并使用1.1中的@ContextConfiguration修饰。@MyTestConfig中定义了value、groovyScripts和xmlFiles三个属性并且在使用@MyTestConfig注解时,如果为这三个属性中的一个属性赋值,都等同于为@ContextConfiguration注解的locations属性赋值,由此其实@MyTestConfig中的这三个属性其实互为隐式别名。

   @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 {};
   }

  4)别名传递

  如下1.4定义了一个@GroovyOrXmlTestConfig注解并使用@MyTestConfig注解修饰,其中含有groovy和xml两个属性,groovy是@MyTestConfig注解的groovyScripts的别名,而@MyTestConfig的groovyScripts又是@ContextConfiguration的locations属性的别名,同时xml属性也是@ContextConfiguration的locations属性的别名,因此groovy属性和xml属性其实也是互为别名的。

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

 

posted @ 2022-12-05 02:21  wuyiping  阅读(510)  评论(0编辑  收藏  举报