源码分析:Spring 合并注解 - MergedAnnotations

原生 JDK 获取注解太麻烦,Spring 封装工具类 MergedAnnotations

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
@Repository
class Animal {

}

class Cat extends Animal {

}

// 2024-05-10 16:03
public static void main(String[] args) throws Throwable {
// 1. 获取不到内部注解
Assert.isNull(Animal.class.getAnnotation(Component.class));
Assert.notNull(Animal.class.getAnnotation(Repository.class));

// 2. 获取不到父类的注解
Assert.isNull(Cat.class.getAnnotation(Component.class));
Assert.isNull(Cat.class.getAnnotation(Repository.class));


// MergedAnnotations 工具类
// - SearchStrategy.DIRECT 仅当前类(默认)
// - SearchStrategy.INHERITED_ANNOTATIONS 当前类 + 父类 ( @Inherited注解修饰的注解 )
// - SearchStrategy.SUPERCLASS 当前类 + 父类
// - SearchStrategy.TYPE_HIERARCHY 当前类 + 父类 + 接口
// - SearchStrategy.TYPE_HIERARCHY_AND_ENCLOSING_CLASSES 当前类 + 父类 + 接口 + 外部类 ( 当前类是内部类时才有外部类 )
Assert.isTrue(MergedAnnotations.from(Animal.class).isPresent(Component.class));
Assert.isTrue(MergedAnnotations.from(Animal.class).isPresent(Repository.class));

Assert.isTrue(MergedAnnotations.from(Cat.class, SearchStrategy.TYPE_HIERARCHY).isPresent(Component.class));
Assert.isTrue(MergedAnnotations.from(Cat.class, SearchStrategy.TYPE_HIERARCHY).isPresent(Repository.class));

// 获取注解
MergedAnnotation<Repository> mergedAnnotation = MergedAnnotations.from(Cat.class, SearchStrategy.TYPE_HIERARCHY).get(Repository.class);
}