原文地址:https://blog.csdn.net/wolfcode_cn/article/details/80654730

在Spring的众多注解中,经常会发现很多注解的不同属性起着相同的作用,比如@RequestMapping的value属性和path属性,这就需要做一些基本的限制,比如value和path的值不能冲突,比如任意设置value或者设置path属性的值,都能够通过另一个属性来获取值等等。为了统一处理这些情况,Spring创建了@AliasFor标签。

使用

@AliasFor标签有几种使用方式。

1,在同一个注解内显示使用;

比如在@RequestMapping中的使用示例:

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Mapping
public @interface RequestMapping { @AliasFor("path")
String[] value() default {}; @AliasFor("value")
String[] path() default {}; //...
}

又比如@ContextConfiguration注解中的value和locations属性:

@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface ContextConfiguration {
@AliasFor("locations")
String[] value() default {}; @AliasFor("value")
String[] locations() default {};
//...
}

  

在同一个注解中成对使用即可,比如示例代码中,value和path就是互为别名。但是要注意一点,@AliasFor标签有一些使用限制,但是这应该能想到的,比如要求互为别名的属性属性值类型,默认值,都是相同的,互为别名的注解必须成对出现,比如value属性添加了@AliasFor(“path”),那么path属性就必须添加@AliasFor(“value”),另外还有一点,互为别名的属性必须定义默认值

那么如果违反了别名的定义,在使用过程中就会报错,我们来做个简单测试:

@ContextConfiguration(value = "aa.xml", locations = "bb.xml")
public class AnnotationUtilsTest {
@Test
public void testAliasfor() {
ContextConfiguration cc = AnnotationUtils.findAnnotation(getClass(),
ContextConfiguration.class);
System.out.println(
StringUtils.arrayToCommaDelimitedString(cc.locations()));
System.out.println(StringUtils.arrayToCommaDelimitedString(cc.value()));
}
}

  

执行测试,报错;value和locations互为别名,不能同时设置;

稍微调整一下代码:

@MyAnnotation
@ContextConfiguration(value = "aa.xml", locations = "aa.xml")
public class AnnotationUtilsTest {

  

运行测试,均打印出:

aa.xml
aa.xml

  

2,显示的覆盖元注解中的属性;

先来看一段代码:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = AopConfig.class)
public class AopUtilsTest {

  

这段代码是一个非常熟悉的基于JavaConfig的Spring测试代码;假如现在我有个癖好,我觉得每次写@ContextConfiguration(classes = AopConfig.class)太麻烦了,我想写得简单一点,我就可以定义一个这样的标签:

@Retention(RetentionPolicy.RUNTIME)
@ContextConfiguration
public @interface STC { @AliasFor(value = "classes", annotation = ContextConfiguration.class)
Class<?>[] cs() default {}; }

  

1,因为@ContextConfiguration注解本身被定义为@Inherited的,所以我们的STC注解即可理解为继承了@ContextConfiguration注解;

2,我觉得classes属性太长了,所以我创建了一个cs属性,为了让这个属性等同于@ContextConfiguration属性中的classes属性,我使用了@AliasFor标签,分别设置了value(即作为哪个属性的别名)和annotation(即作为哪个注解);

使用我们的STC:

@RunWith(SpringJUnit4ClassRunner.class)
@STC(cs = AopConfig.class)
public class AopUtilsTest { @Autowired
private IEmployeeService service;

  

正常运行;
这就是@AliasFor标签的第二种用法,显示的为元注解中的属性起别名;这时候也有一些限制,比如属性类型,属性默认值必须相同;当然,在这种使用情况下,@AliasFor只能为作为当前注解的元注解起别名;

3,在一个注解中隐式声明别名;
这种使用方式和第二种使用方式比较相似,我们直接使用Spring官方文档的例子:

 @ContextConfiguration
public @interface MyTestConfig { @AliasFor(annotation = ContextConfiguration.class, attribute = "locations")
String[] value() default {}; @AliasFor(annotation = ContextConfiguration.class, attribute = "locations")
String[] groovyScripts() default {}; @AliasFor(annotation = ContextConfiguration.class, attribute = "locations")
String[] xmlFiles() default {};
}

  

可以看到,在MyTestConfig注解中,为value,groovyScripts,xmlFiles都定义了别名@AliasFor(annotation = ContextConfiguration.class, attribute = “locations”),所以,其实在这个注解中,value、groovyScripts和xmlFiles也互为别名,这个就是所谓的在统一注解中的隐式别名方式;

4,别名的传递;
@AliasFor注解是允许别名之间的传递的,简单理解,如果A是B的别名,并且B是C的别名,那么A是C的别名;
我们看一个例子:

 @MyTestConfig
public @interface GroovyOrXmlTestConfig { @AliasFor(annotation = MyTestConfig.class, attribute = "groovyScripts")
String[] groovy() default {}; @AliasFor(annotation = ContextConfiguration.class, attribute = "locations")
String[] xml() default {};
}

  

1,GroovyOrXmlTestConfig把 @MyTestConfig(参考上一个案例)作为元注解;
2,定义了groovy属性,并作为MyTestConfig中的groovyScripts属性的别名;
3,定义了xml属性,并作为ContextConfiguration中的locations属性的别名;
4,因为MyTestConfig中的groovyScripts属性本身就是ContextConfiguration中的locations属性的别名;所以xml属性和groovy属性也互为别名;
这个就是别名的传递性;

原理

明白@AliasFor标签的使用方式,我们简单来看看@AliasFor标签的使用原理;
首先来看看该标签的定义:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface AliasFor { @AliasFor("attribute")
String value() default ""; @AliasFor("value")
String attribute() default ""; Class<? extends Annotation> annotation() default Annotation.class; }

  

可以看到,@AliasFor标签自己就使用了自己,为value属性添加了attribute属性作为别名;

那么就把这个注解放在我们需要的地方就可以了么?真就这么简单么?我们来做一个例子:
1,创建一个注解

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface MyAnnotation { @AliasFor("alias")
String value() default ""; @AliasFor("value")
String alias() default ""; }

  

在该注解中,我们让alias和value属性互为别名;
2,完成测试类:

@MyAnnotation(value = "aa", alias = "bb")
public class AnnotationUtilsTest { @Test
public void testAliasfor2() {
MyAnnotation ann = getClass().getAnnotation(MyAnnotation.class);
System.out.println(ann.value());
System.out.println(ann.alias());
}
}

  

我们将MyAnnotation放在AnnotationUtilsTest上,可以看到,我们故意将value和alias值设置为不一样的,然后在测试代码中分别获取value()和alias()的值,结果打印:
aa
bb

WTF?和预期的不一样?原因很简单,AliasFor是Spring定义的标签,要使用他,只能让Spring来处理,修改测试代码:

@MyAnnotation(value = "aa", alias = "bb")
public class AnnotationUtilsTest { @Test
public void testAliasfor3() {
MyAnnotation ann = AnnotationUtils.findAnnotation(getClass(),
MyAnnotation.class);
System.out.println(ann.value());
System.out.println(ann.alias());
}
}

  

这次我们使用Spring的AnnotationUtils工具类的findAnnotation方法来获取标签,然后再次打印value()和alias()值:


如愿报错;所以,使用@AliasFor最需要注意一点的,就是只能使用Spring的AnnotationUtils工具类来获取;

而真正在起作用的,是AnnotationUtils工具类中的<A extends Annotation> A synthesizeAnnotation(A annotation, AnnotatedElement annotatedElement)方法;
这个方法传入注解对象,和这个注解对象所在的类型,返回一个经过处理(这个处理就主要是用于处理@AliasFor标签)之后的注解对象,简单说,这个方法就是把A注解对象—-(经过处理)——>支持AliasFor的A注解对象,我们来看看其中的关键代码:

DefaultAnnotationAttributeExtractor attributeExtractor =
new DefaultAnnotationAttributeExtractor(annotation, annotatedElement);
InvocationHandler handler =
new SynthesizedAnnotationInvocationHandler(attributeExtractor);
return (A) Proxy.newProxyInstance(annotation.getClass().getClassLoader(),
new Class<?>[] {(Class<A>) annotationType, SynthesizedAnnotation.class}, handler);

  

可以看到,本质原理就是使用了AOP来对A注解对象做了次动态代理,而用于处理代理的对象为SynthesizedAnnotationInvocationHandler;我们来看看SynthesizedAnnotationInvocationHandler中的重要处理代码:

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (isEqualsMethod(method)) {
return annotationEquals(args[0]);
}
if (isHashCodeMethod(method)) {
return annotationHashCode();
}
if (isToStringMethod(method)) {
return annotationToString();
}
if (isAnnotationTypeMethod(method)) {
return annotationType();
}
if (!isAttributeMethod(method)) {
String msg = String.format("Method [%s] is unsupported for synthesized annotation type [%s]", method,
annotationType());
throw new AnnotationConfigurationException(msg);
}
return getAttributeValue(method);
}

  

在invoke(即拦截方法中,这个拦截方法就是在注解中获取属性值的方法,不要忘了,注解的属性实际上定义为接口的方法),其次判断,如果当前执行的方法不是equals、hashCode、toString、或者属性是另外的注解,或者不是属性方法,之外的方法(这些方法就是要处理的目标属性),都调用了getAttributeValue方法,所以我们又跟踪到getAttributeValue方法的重要代码:

String attributeName = attributeMethod.getName();
Object value = this.valueCache.get(attributeName);
if (value == null) {
value = this.attributeExtractor.getAttributeValue(attributeMethod);

  

这里我们重点关注的是如果没有缓存到值(这个先不用管),直接调用attributeExtractor.getAttributeValue方法获取属性值,那么,很容易猜到,如果属性有@AliasFor注解,就应该是这个方法在处理;那我们来看看这个方法又在做什么事情:

attributeExtractor是一个AnnotationAttributeExtractor类型,这个对象是在构造SynthesizedAnnotationInvocationHandler时传入的,默认是一个DefaultAnnotationAttributeExtractor对象;而DefaultAnnotationAttributeExtractor是继承AbstractAliasAwareAnnotationAttributeExtractor,看名字,真正的处理AliasFor标签的动作,应该就在这里面,于是继续看代码:

public final Object getAttributeValue(Method attributeMethod) {
String attributeName = attributeMethod.getName();
Object attributeValue = getRawAttributeValue(attributeMethod); List<String> aliasNames = this.attributeAliasMap.get(attributeName);
if (aliasNames != null) {
Object defaultValue = AnnotationUtils.getDefaultValue(getAnnotationType(), attributeName);
for (String aliasName : aliasNames) {
Object aliasValue = getRawAttributeValue(aliasName); if (!ObjectUtils.nullSafeEquals(attributeValue, aliasValue) &&
!ObjectUtils.nullSafeEquals(attributeValue, defaultValue) &&
!ObjectUtils.nullSafeEquals(aliasValue, defaultValue)) {
throw new AnnotationConfigurationException(...)
}
if (ObjectUtils.nullSafeEquals(attributeValue, defaultValue)) {
attributeValue = aliasValue;
}
}
} return attributeValue;
}

  

对原代码做了些改造,但是我们能清晰的看到重点:
1,首先正常获取当前属性的值;
2,List<String> aliasNames = this.attributeAliasMap.get(attributeName);得到所有的标记为别名的属性名称;
3,Object aliasValue = getRawAttributeValue(aliasName);遍历获取所有别名属性的值;
4,三个重要判断,attributeValue、aliasValue、defaultValue相同,我们前面介绍的@AliasFor标签的传递性也是在这里体现;如果不相同,直接抛出异常;否则正常返回属性值;

至此,AliasFor的执行过程分析完毕;

小结

类似@AliasFor这样的注解,在Spring框架中比比皆是,而每一个这样的细节的点,都值得我们去体会。我们常常说Spring框架非常复杂,因为在每一个点的实现,都要考虑很多健壮性和扩展性的问题,这些,都是我们值得去研究的。

Spring @AliasFor的更多相关文章

  1. spring cloud 启动报错-must be declared as an @AliasFor [serviceId], not [name].

    项目加入FeignClient后再启动就报错,具体报错信息如下: org.springframework.core.annotation.AnnotationConfigurationExceptio ...

  2. 关于如何使用Spring里@AliasFor注解进行注解的封装

    不知道大家每次使用Spring boot的时候有没有看过它启动类里 @SpringBootApplication这个注解呢?众所周知,这个注解是一个复合注解,但是注解是不能继承元注解的属性的,也就是说 ...

  3. spring core:@AliasFor的派生性

    spring对Annotation的派生性应用可谓炉火纯青,在spring core:@Component的派生性讲过支持层次上派生性,而属性上派生的需求则借助了@AliasFor,它是从spring ...

  4. Spring MVC控制器

    Spring MVC中控制器用于解析用户请求并且转换为模型以提供访问应用程序的行为,通常用注解方式实现. org.springframework.stereotype.Controller注解用于声明 ...

  5. Spring MVC 学习总结(二)——控制器定义与@RequestMapping详解

    一.控制器定义 控制器提供访问应用程序的行为,通常通过服务接口定义或注解定义两种方法实现. 控制器解析用户的请求并将其转换为一个模型.在Spring MVC中一个控制器可以包含多个Action(动作. ...

  6. spring之ControllerAdvice注解

    @ControllerAdvice是Spring 3.2新增的注解,主要是用来Controller的一些公共的需求的低侵入性增强提供辅助,作用于@RequestMapping标注的方法上. Contr ...

  7. Spring MVC异常处理详解(转)

    下图中,我画出了Spring MVC中,跟异常处理相关的主要类和接口. 在Spring MVC中,所有用于处理在请求映射和请求处理过程中抛出的异常的类,都要实现HandlerExceptionReso ...

  8. Spring Boot 系列教程6-全局异常处理

    @ControllerAdvice源码 package org.springframework.web.bind.annotation; import java.lang.annotation.Ann ...

  9. 【spring boot】SpringBoot初学(2) - properties配置和读取

    前言 只是简单的properties配置学习,修改部分"约定"改为自定义"配置".真正使用和遇到问题是在细看. 一.主要 核心只是demo中的: @Proper ...

随机推荐

  1. 系列文章--Enterprise Library文章总结

    自Enterprise Library 1.1 推出以来,Terry写了一系列的关于Enterprise Library的文章,其中得到了很多朋友的支持,在这里一并表示感谢.为了方便大家的阅读,这里我 ...

  2. PHP面向对象——三大基本特性与五大基本原则

    三大特性是:封装.继承.多态 所谓封装,也就是把客观事物封装成抽象的类,并且类可以把自己的数据和方法只让可信的类或者对象操作,对不可信的进行信息隐藏. 封装是面向对象的特征之一,是对象和类概念的主要特 ...

  3. AppScan9.0.3.5漏洞扫描记录

    1.跨站点脚本编制 这个安全漏洞拿cookie做文章,而且是将前端的一些弹窗方法,要么通过脚本注入,要么通过url.encode之后注入,看几个变异的版本: 版本一: cookie  从以下位置进行控 ...

  4. 【转】无需root Android 4.4现已支持显示电量百分比

    原文网址:http://android.tgbus.com/shouji/news/201311/481145.shtml 现如今,大多数安卓设备.第三方ROM都可以在状态栏以百分比的形式精确显示剩余 ...

  5. Linux的POSIX线程属性

    创建POSIX线程的函数为 int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routin ...

  6. nginx限制请求之四:目录进行IP限制

    相关文章: <高可用服务设计之二:Rate limiting 限流与降级> <nginx限制请求之一:(ngx_http_limit_conn_module)模块> <n ...

  7. Mysql无法创建外键的原因 !!!

    在MySQL中创建外键时,经常会遇到问题而失败,这是因为Mysql中还有很多细节需要我们去留意,我自己总结并查阅资料后列出了以下几种常见原因. 1.  两个字段的类型或者大小不严格匹配.例如,如果一个 ...

  8. 安装Elastix-2.4版本

    首先,下载Elastix地址:http://www.elastix.org,下载里面的2.4版本 第一步:选择安装,Enter 选择语言,默认就行 选择us,默认 选择全部 选择默认分区,点击OK 配 ...

  9. 在centOS5.9安装mysql

    网上的信息实在是太乱了,好多出了错的,我这个是自己亲自配置,其实就简简单单的几步:如果你的系统里有以前遗留的文件,用rm -rf文件名删除掉 1.安装MySQL客服端和服务器端             ...

  10. supervisor 管理

    Supervisor是用Python开发的一套通用的进程管理程序,能将一个普通的命令行进程变为后台daemon,并监控进程状态,异常退出时能自动重启.它是通过fork/exec的方式把这些被管理的进程 ...