源码分析:Spring 合并注解 - MergedAnnotations 发表于 2024-05-08 | 分类于 ---Spring , ---源码 | 原生 JDK 获取注解太麻烦,Spring 封装工具类 MergedAnnotations 1234567891011121314151617181920212223242526272829303132333435@Repositoryclass Animal {}class Cat extends Animal {}// 2024-05-10 16:03public 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);}