使用场景
注释中的显式别名:在单个注释中,@AliasFor可以在一对属性上声明,以表示它们是彼此可以互换的别名
元注释中属性的显式别名:如果@Aliasfor的注释属性设置为与声明它的注释不同的注释,则该属性将被解释为元注释中属性的别名(即显式元注释属性重写)。这使得能够对注释层次结构中重写的属性进行细粒度控制。实际上,使用@alias for甚至可以为元注释的value属性声明别名。
示例:注释中的显式别名
在@ContextConfiguration中,值value和位置locations是彼此的显式别名。 就是说他们都可以分别代表自己和对方
//@RequestMapping(path= "index",method = RequestMethod.GET) 等同
@RequestMapping(value = "index",method = RequestMethod.GET)
public String index(Map<String,Object> map){
return "index";
}
使用要求
批注中的显式别名:
@AliasFor(annotation = EnableAutoConfiguration.class, attribute = "excludeName")
String[] excludeName() default {};
@AliasFor(annotation = EnableAutoConfiguration.class, attribute = "excludeName")
String[] excludeName() default {};
- 构成别名对的每个属性都必须用@AliasFor注释,并且属性或值必须引用该对中的另一个属性。
- 别名属性必须声明相同的返回类型。
- 别名属性必须声明默认值。
- 别名属性必须声明相同的默认值。
- 不应声明批注。
- 元批注中属性的显式别名:
- 作为元批注中属性别名的属性必须使用@aliasAfor进行批注,并且属性必须引用元批注(原始类)中的属性。
- 别名属性必须声明相同的返回类型。
- 批注必须引用元批注。
- 引用的元批注必须是声明@AliasFor的批注类上的元批注。
批注中的隐式别名:
属于一组隐式别名的每个属性都必须使用@AliasFor进行注释,并且属性必须引用同一元注释中的同一属性(通过注释层次结构中的其他显式元注释属性重写直接或传递)。
- 别名属性必须声明相同的返回类型。
- 别名属性必须声明默认值。
- 别名属性必须声明相同的默认值。
- 批注必须引用适当的元批注。
- 引用的元批注必须是声明@AliasFor的批注类上的元批注。
示例:注释中的显式别名
在@ContextConfiguration中,值和位置是彼此的显式别名。
public @interface ContextConfiguration {
@AliasFor("locations")
String[] value() default {};
@AliasFor("value")
String[] locations() default {};
// ...
}
示例:元批注中属性的显式别名
在@XmlTestConfig中,xmlFiles是@ContextConfiguration中位置的显式别名。换句话说,xmlFiles重写@ContextConfiguration中的locations属性。
@ContextConfiguration
public @interface XmlTestConfig {
@AliasFor(annotation = ContextConfiguration.class, attribute = "locations")
String[] xmlFiles();
}
示例:注释中的隐式别名
在@MyTestConfig中,value、groovyscript和xmlFiles都是@ContextConfiguration中locations属性的显式元注释属性重写。因此,这三个属性也是彼此的隐式别名。
也就是说value、groovyscript和xmlFiles都可以分别代表对应自己
如value是ContextConfiguration中locations属性的显示别名是groovyscript和xmlFiles的隐式别名其他同理
@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 {};
}
示例:注释中的可传递隐式别名
在@GroovyOrXmlTestConfig中,groovy是对@MyTestConfig中groovyscript属性的显式重写;而xml是对@ContextConfiguration中locations属性的显式重写。此外,groovy和xml是相互传递的隐式别名,因为它们都有效地覆盖了@ContextConfiguration中的locations属性。
@MyTestConfig
public @interface GroovyOrXmlTestConfig {
@AliasFor(annotation = MyTestConfig.class, attribute = "groovyScripts")
//groovyScripts重写 ContextConfiguration中的locations。 groovy重写MyTestConfig的
//groovyScripts
String[] groovy() default {};
@AliasFor(annotation = ContextConfiguration.class, attribute = "locations")
String[] xml() default {};
}