注解的含义
顾名思义 @AliasFor 表示别名,它可以注解到自定义注解的两个属性上,表示这两个互为别名,也就是说这两个属性其实同一个含义。
同时若自定义注解继承了另一个注解,要想让调用方能够设置继承过来的属性值,就必须在自定义注解中重新定义一个属性,同时声明该属性是父注解某个属性的别名。
注解的使用方法
互为别名
在下面的例子中,value属性和location属性互为别名,此时使用的时候可以指定属性名来设置属性值,也能使用缺省属性名的方法。
在两个属性互为别名的使用情况下,只需要设置@AliasFor注解的attribute属性(它与value互为别名),它表示与注解标注的属性互为别名的另一个属性的名字。
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Inherited
public @interface MyAnnotation {
@AliasFor(attribute = "location")
String value() default "";
@AliasFor(attribute = "value")
String location() default "";
}
继承时使用
spring中有时候一个类上面标记很多注解。实际上Java注解可以进行继承(也就是把多个注解合并成1个)
在继承父注解的属性时,可以通过value属性指定被注解的属性继承的是父注解的哪个属性;也能缺省,这种情况下默认继承父注解中同名的属性名。例子如下:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Inherited
@MyAnnotation
public @interface SubMyAnnotation {
@AliasFor(value="location",annotation=MyAnnotation.class)
String subLocation() default "";
//缺省指明继承的父注解的中的属性名称,则默认继承父注解中同名的属性名
@AliasFor(annotation=MyAnnotation.class)
String value() default "";
}