Springboot @AliasFor使用

场景1:在同一个注解内,对两个不同的属性一起使用,互为别名,比如@RequestMapping中path和value成对使用,互为别名。
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Mapping
public @interface RequestMapping {
    String name() default "";

    @AliasFor("path") // 此时path和value值是一样的,如果不一样会报错
    String[] value() default {};

    @AliasFor("value") // 此时path和value值是一样的,如果不一样会报错
    String[] path() default {};
    ... 其它略 ....
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
使用如下:

// 正解:path和value都为"/getbaidu"
@RequestMapping(path="/getbaidu", method=RequestMethod.GET)
// 正解:path和value都为"/getbaidu"
@RequestMapping(value="/getbaidu", method=RequestMethod.GET)
// 正解:path和value都为"/getbaidu"
@RequestMapping(path="/getbaidu", value="/getbaidu", method=RequestMethod.GET)
// 错误:因为path和value已经绑定,互为别名,因此值必须一样
@RequestMapping(path="/getbaidu", value="/getgoogle", method=RequestMethod.GET)
1
2
3
4
5
6
7
8
9
此外,注意一点,因为互为别名,因此path和value的默认值,即default值必须一样
场景2:为其它注解别名
还是以@RequestMapping为例,我们为@RequestMapping换个名称:NewRM
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Mapping
@RequestMapping // 这个地方不能少,不知道为什么????
public @interface NewRM {

    @AliasFor(value="path", annotation = RequestMapping.class)
    String[] ph() default {};
    @AliasFor(value="method", annotation = RequestMapping.class)
    RequestMethod[] md() default {};
    ... 其它略 ....
}
1
2
3
4
5
6
7
8
9
10
11
12
13
这样设置以后,下面两种方式就变成完全等价的了:
    // 这两行注解是完全等价的
    @RequestMapping(path="/getbaidu", method=RequestMethod.GET)
    @NewRM(ph="/getbaidu", md = RequestMethod.GET)
1
2
3
场景3:传递别名(跟场景2很类似):再来看NewRM:
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Mapping
@RequestMapping // 这个地方不能少,不知道为什么????
public @interface NewRM {

    @AliasFor(value="path", annotation = RequestMapping.class)
    String[] ph() default {};
    @AliasFor(value="method", annotation = RequestMapping.class)
    RequestMethod[] md() default {};
    // 这里用了attribute传递,而在AliasFor中,attribute与value是相通的,因此ph2等价于ph
    @AliasFor(attribute="path", annotation = RequestMapping.class)
    String[] ph2() default {};
    ... 其它略 ....
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
因此,下面三种方式是等价的:
    // 这三行注解是完全等价的
    @RequestMapping(path="/getbaidu", method=RequestMethod.GET)
    @NewRM(ph="/getbaidu", md = RequestMethod.GET)
    @NewRM(ph2="/getbaidu", md = RequestMethod.GET)
1
2
3
4
更加深层次的介绍,参见这里:https://www.jianshu.com/p/869ed7037833
 

原文地址:https://blog.csdn.net/zhaole524/article/details/80836172

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值