同一注解类中的@AliasFor
这种场景比较简单,首先定义注解
package com.uu.annotation;
import org.springframework.core.annotation.AliasFor;
import java.lang.annotation.*;
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SameAnnotation {
@AliasFor("title")
String name() default "";
@AliasFor("name")
String title() default "";
}
测试类,注意由于 @AliasFor 是spring专有的注解,这里需要用spring框架提供的api来获取注解的值
package com.uu;
import com.uu.annotation.SameAnnotation;
import org.junit.Test;
import org.springframework.core.annotation.AnnotationUtils;
@SameAnnotation(name = "999")
public class DemoTest {
@Test
public void test(){
SameAnnotation a = AnnotationUtils.findAnnotation(DemoTest.class, SameAnnotation.class);
System.out.println(a.name());
System.out.println(a.title());
}
}
打印结果
这里我们只在标签里设置了 name属性,但是title我们也获得了相同的值
不同注解类间的@AliasFor
首先定义两个注解
第一个注解:
package com.uu.annotation;
import java.lang.annotation.*;
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface MyAnnotation {
String name() default "";
}
第二个注解:
在注解类上标注第一个注解,因为这种场景是组合注解的扩展;并在属性name1上设置 @AliasFor
package com.uu.annotation;
import org.springframework.core.annotation.AliasFor;
import java.lang.annotation.*;
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@MyAnnotation
public @interface DemoAnnotation {
@AliasFor(annotation = MyAnnotation .class,attribute = "name")
String name1() default "";
}
测试类
package com.uu;
import com.uu.annotation.DemoAnnotation;
import com.uu.annotation.MyAnnotation;
import org.junit.Test;
import org.springframework.core.annotation.AnnotatedElementUtils;
@DemoAnnotation(name1 = "999")
public class DemoTest {
@Test
public void test(){
MyAnnotation bb = AnnotatedElementUtils.getMergedAnnotation(DemoTest.class, MyAnnotation.class);
System.out.println(bb.name());
}
}
这里要注意使用 AnnotatedElementUtils的api ,否则获取不到值(这里我入坑很久没有找到方向出来,血泪史)
打印结果:
我们在测试类上标注的是DemoAnnotation但是我们可以获得MyAnnotation类型封装;
小知识
JAVA语言规范规定注解之间不能有继承关系,Spring Framework则通过元注解的方式巧妙的解决了注解之间的这种类似“继承”的关系,比如 @Component 和 @Service之间的关系;
@Component就是一个元注解,可以用在其他注解上进行标注,然后Spring提供了一套API来实现这一些列操作