源码分析:Spring 注解别名 - @AliasFor

总结

1
2
3
4
5
6
7
8
9
--------------------------------------------------------------------
# Spring 解析 @AliasFor
AnnotationTypeMapping.resolveAliasedForTargets

本质(简要说明):
根据传入名称 获取方法 Method,invoke 调用方法获取结果
-> 结果:非空 -> 返回
-> 结果:空 -> 根据 Method 获取 @AliasFor 属性,获取 aliasMethod 调用获取结果
--------------------------------------------------------------------

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package com.taopanfeng.junit.spring._004_AliasFor;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import org.springframework.core.annotation.AliasFor;
import org.springframework.core.annotation.MergedAnnotation;
import org.springframework.core.annotation.MergedAnnotations;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import java.util.Arrays;

/**
* 描述
*
* @author 陶攀峰
* @date 2024-05-10 18:02
*/
// @MyTest.MyComponent(value = "abc", name = "def")// 不可以同时声明
@MyTest.MyComponent("abc")
public class MyTest {

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@interface MyComponent {
@AliasFor(attribute = "name")
String value() default "";

@AliasFor(attribute = "value")
String name() default "";
}

// 2024-05-10 18:03
public static void main(String[] args) throws Throwable {
// 测试1:Spring获取
MergedAnnotation<MyComponent> anno = MergedAnnotations.from(MyTest.class).get(MyComponent.class);
Assert.equals(anno.getString("value"), "abc");
Assert.equals(anno.getString("name"), "abc");

// 测试2:原生代码获取
MyComponent anno2 = MyTest.class.getAnnotation(MyComponent.class);
Method method = Arrays.stream(MyComponent.class.getDeclaredMethods()).filter(e -> e.getName().equals("name")).findFirst().orElse(null);
String value = (String) method.invoke(anno2);
String aliasName = method.getAnnotation(AliasFor.class).attribute();

if (StrUtil.isBlank(value)) {
Method aliasMethod = Arrays.stream(MyComponent.class.getDeclaredMethods()).filter(e -> e.getName().equals(aliasName)).findFirst().orElse(null);
value = (String) aliasMethod.invoke(anno2);
}
System.out.println("name:" + value);// name:abc
}

}