栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

@AliasFor注解的的使用:Spring子注解的属性值无法传递给父注解

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

@AliasFor注解的的使用:Spring子注解的属性值无法传递给父注解

@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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/880933.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号