@Component
public @interface Service {
@AliasFor(annotation = Component.class)
String value() default "";
}
如上述代码,@Service#value为@Component#value的别名,@Service#value的值可以映射到@Component#value。
(这里我们将@Service,@Component看做一种特继承关系,@Component是父注解,@Service是子注解,@Service#value覆盖@Component#value)
demo
@Service("serviceAlias")
public class ServiceAlias {
public static void main(String[] args) {
Component component = AnnotationUtils.getAnnotation(ServiceAlias.class, Component.class);
System.out.println(component);
Component component2 = AnnotatedElementUtils.getMergedAnnotation(ServiceAlias.class, Component.class);
System.out.println(component2);
}
}
输出结果如下:
@org.springframework.stereotype.Component(value=) @org.springframework.stereotype.Component(value=serviceAlias)
可以看到,虽然ServiceAlias上只有@Service,但通过AnnotationUtils.getAnnotation方法会解析得到@Component,而通过AnnotatedElementUtils.getMergedAnnotation方法还可以将@Service#value的值赋给@Component#value。
因此,可通过AnnotatedElementUtils.getMergedAnnotation方法将Spring子注解的属性值传递给父注解。
参考:SpringBoot深入理解 -- @AliasFor注解的作用 - SegmentFault 思否本文解析SpringBoot中重要注解@AliasFor注解的作用,对于理解SpringBoot和后面阅读SpringBoot源码都很有帮助。https://segmentfault.com/a/1190000022613166?utm_source=tag-newest



