1.概念
@AliasFor注解可以为注解本身提供别名
2.配对别名
public class AliasForDemo {
public static class TestBean
{
@AliasFor("test")
public void test()
{}
}
@Test
public void test1() throws NoSuchMethodException {
Method method=TestBean.class.getMethod("test",null);
AliasFor aliasFor1=method.getAnnotation(AliasFor.class);
AliasFor aliasFor2=AnnotationUtils.synthesizeAnnotation(aliasFor1,null);
AliasFor aliasFor3=AnnotationUtils.getAnnotation(method,AliasFor.class);
}
@Test
public void test2() throws NoSuchMethodException {
ContextConfig contextConfig1 = SimpleConfigTestCase.class.getAnnotation(ContextConfig.class);
ContextConfig contextConfig2=AnnotationUtils.synthesizeAnnotation(contextConfig1,null);
ContextConfig contextConfig3=AnnotationUtils.getAnnotation(SimpleConfigTestCase.class,ContextConfig.class);
}
@ContextConfig("simple.xml")
static class SimpleConfigTestCase {
}
@Retention(RetentionPolicy.RUNTIME)
@interface ContextConfig {
@AliasFor("location")
String value() default "";
@AliasFor("value")
String location() default "";
Class<?> klass() default Object.class;
}
}
输出结果:
可以看到,如果使用jdk内置方法获取注解是无法使用别名特性的,因为该特性是spring提供,所以可以调用AnnotationUtils.synthesizeAnnotation方法来获取一个动态代理注解
也可以直接调用AnnotationUtils.getAnnotation来获取注解,内部会调用AnnotationUtils.synthesizeAnnotation方法
参考:
https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/core/annotation/AliasFor.html
http://ifeve.com/annotation-programming-model/