文章目录
@AliasFor
1. @AliasFor 什么作用?
@AliasFor 别名,是Spring的一个注解。Spring针对这个注解有专门处理的逻辑。作用其实相当于等效,当注解加到某个注解上,当前这个注解都有了别名标记的功能。
2. @AliasFor的源码结构
// 这个三个注解是元注解。
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface AliasFor {
/**
* Alias for {@link #attribute}.
* <p>Intended to be used instead of {@link #attribute} when {@link #annotation}
* is not declared — for example: {@code @AliasFor("value")} instead of
* {@code @AliasFor(attribute = "value")}.
*/
@AliasFor("attribute")
String value() default "";
/**
* The name of the attribute that <em>this</em> attribute is an alias for.
* @see #value
*/
@AliasFor("value")
String attribute() default "";
/**
* The type of annotation in which the aliased {@link #attribute} is declared.
* <p>Defaults to {@link Annotation}, implying that the aliased attribute is
* declared in the same annotation as <em>this</em> attribute.
*/
Class<? extends Annotation> annotation() default Annotation.class;
}
内部的值:
- value 与 attribute ,由上可以看出两个互为别名,所以只需要填写其中的一个值即可。
- annotation ,这个值,用于将当前的注解标记成某个注解,可以实现当前注解和某个注解共同的作用。
3. @AliasFor的用法
3.1 用法一:同个注解中的两个属性互为别名
查看@RequestMapping注解
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Mapping
public @interface RequestMapping {
String name() default "";
// 此处path 与 value 互为别名。说明两个值是一个意思
@AliasFor("path")
String[] value() default {};
@AliasFor("value")
String[] path() default {};
RequestMethod[] method() default {};
String[] params() default {};
String[] headers() default {};
String[] consumes() default {};
String[] produces() default {};
}
当同个注解中的两个属性互为别名的时候,无论指明设置哪个属性名设置属性值,另一个属性名也是同样属性值。若两个都指明属性值,要求值必须相同,否则会报错。
3.2 用法二:继承父注解的属性,使其拥有更强大的功能
java本身自带的注解,不提供继承功能。所以我们想复用某个注解的功能,就要靠@AliasFor来实现,看一下@Configuration注解。
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component // 此处要写上父类的注解
public @interface Configuration {
// 此时@Configuration的value等价于@Component的Value。说明@Configuration也有@Component一样的功能。
@AliasFor(annotation = Component.class)
String value() default "";
boolean proxyBeanMethods() default true;
}
再看一个@Controller注解,
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Controller {
// 我们都知道@Controller有@Component的功能,就是通过@AliasFor来实现的。
@AliasFor(annotation = Component.class)
String value() default "";
}
3. @AliasFor的实践
自己来编写一个注解,继承Component的功能。
model类
配置类:
测试一下: