Spring 元信息

ClassMetadata

  1. public interface ClassMetadata {
  2. /**
  3. * 类名
  4. */
  5. String getClassName();
  6. /**
  7. * 是否是接口
  8. */
  9. boolean isInterface();
  10. /**
  11. * 是否是注解
  12. */
  13. boolean isAnnotation();
  14. /**
  15. * 是否是超类
  16. */
  17. boolean isAbstract();
  18. /**
  19. * 是否允许创建,实例化
  20. */
  21. default boolean isConcrete() {
  22. return !(isInterface() || isAbstract());
  23. }
  24. /**
  25. * 是否有final修饰
  26. */
  27. boolean isFinal();
  28. /**
  29. * 是否独立
  30. */
  31. boolean isIndependent();
  32. /**
  33. * 是否有内部类
  34. */
  35. default boolean hasEnclosingClass() {
  36. return (getEnclosingClassName() != null);
  37. }
  38. /**
  39. * 是否是基础类
  40. */
  41. @Nullable
  42. String getEnclosingClassName();
  43. /**
  44. * 是否有父类
  45. */
  46. default boolean hasSuperClass() {
  47. return (getSuperClassName() != null);
  48. }
  49. /**
  50. * 父类名称
  51. */
  52. @Nullable
  53. String getSuperClassName();
  54. /**
  55. * 实现类名称列表
  56. */
  57. String[] getInterfaceNames();
  58. /**
  59. * 成员列表
  60. * @since 3.1
  61. */
  62. String[] getMemberClassNames();
  63. }

image-20200824094154847

AnnotatedTypeMetadata

  1. public interface AnnotatedTypeMetadata {
  2. /**
  3. * 获取所有注解
  4. */
  5. MergedAnnotations getAnnotations();
  6. /**
  7. * 是否有注解
  8. */
  9. default boolean isAnnotated(String annotationName) {
  10. return getAnnotations().isPresent(annotationName);
  11. }
  12. /**
  13. * 获取注解的属性
  14. */
  15. @Nullable
  16. default Map<String, Object> getAnnotationAttributes(String annotationName) {
  17. return getAnnotationAttributes(annotationName, false);
  18. }
  19. // 省略其他
  20. }

AnnotationMetadata

  1. public interface AnnotationMetadata extends ClassMetadata, AnnotatedTypeMetadata {
  2. /**
  3. * 获取注解名称,全类名
  4. */
  5. default Set<String> getAnnotationTypes() {
  6. return getAnnotations().stream()
  7. .filter(MergedAnnotation::isDirectlyPresent)
  8. .map(annotation -> annotation.getType().getName())
  9. .collect(Collectors.toCollection(LinkedHashSet::new));
  10. }
  11. /**
  12. * 注解全类名
  13. */
  14. default Set<String> getMetaAnnotationTypes(String annotationName) {
  15. MergedAnnotation<?> annotation = getAnnotations().get(annotationName, MergedAnnotation::isDirectlyPresent);
  16. if (!annotation.isPresent()) {
  17. return Collections.emptySet();
  18. }
  19. return MergedAnnotations.from(annotation.getType(), SearchStrategy.INHERITED_ANNOTATIONS).stream()
  20. .map(mergedAnnotation -> mergedAnnotation.getType().getName())
  21. .collect(Collectors.toCollection(LinkedHashSet::new));
  22. }
  23. /**
  24. * 是否包含某个注解
  25. */
  26. default boolean hasAnnotation(String annotationName) {
  27. return getAnnotations().isDirectlyPresent(annotationName);
  28. }
  29. /**
  30. * 是否被某个注解标记过
  31. */
  32. default boolean hasMetaAnnotation(String metaAnnotationName) {
  33. return getAnnotations().get(metaAnnotationName,
  34. MergedAnnotation::isMetaPresent).isPresent();
  35. }
  36. /**
  37. * 是否有注解,类里面有一个注解就返回true
  38. */
  39. default boolean hasAnnotatedMethods(String annotationName) {
  40. return !getAnnotatedMethods(annotationName).isEmpty();
  41. }
  42. /**
  43. * 获取包含注解的方法
  44. */
  45. Set<MethodMetadata> getAnnotatedMethods(String annotationName);
  46. /**
  47. * 通过反射创建一个注解的元信息
  48. */
  49. static AnnotationMetadata introspect(Class<?> type) {
  50. return StandardAnnotationMetadata.from(type);
  51. }
  52. }

MethodMetadata

  1. public interface MethodMetadata extends AnnotatedTypeMetadata {
  2. /**
  3. * 方法名称
  4. */
  5. String getMethodName();
  6. /**
  7. * 方法全路径
  8. */
  9. String getDeclaringClassName();
  10. /**
  11. * 返回值类型
  12. */
  13. String getReturnTypeName();
  14. /**
  15. * 是不是abstrac修饰
  16. */
  17. boolean isAbstract();
  18. /**
  19. * 是否 static 修饰
  20. */
  21. boolean isStatic();
  22. /**
  23. * 是否 final 修饰
  24. */
  25. boolean isFinal();
  26. /**
  27. * 是否重载
  28. */
  29. boolean isOverridable();
  30. }

MetadataReader

  1. public interface MetadataReader {
  2. /**
  3. * Return the resource reference for the class file.
  4. *
  5. * 获取资源
  6. */
  7. Resource getResource();
  8. /**
  9. * Read basic class metadata for the underlying class.
  10. * 获取类的元信息
  11. */
  12. ClassMetadata getClassMetadata();
  13. /**
  14. * Read full annotation metadata for the underlying class,
  15. * including metadata for annotated methods.
  16. *
  17. * 获取注解的元信息
  18. */
  19. AnnotationMetadata getAnnotationMetadata();
  20. }

MetadataReaderFactory

  • 用来创建 MetadataReader
  1. public interface MetadataReaderFactory {
  2. /**
  3. * Obtain a MetadataReader for the given class name.
  4. * @param className the class name (to be resolved to a ".class" file)
  5. * @return a holder for the ClassReader instance (never {@code null})
  6. * @throws IOException in case of I/O failure
  7. */
  8. MetadataReader getMetadataReader(String className) throws IOException;
  9. /**
  10. * Obtain a MetadataReader for the given resource.
  11. * @param resource the resource (pointing to a ".class" file)
  12. * @return a holder for the ClassReader instance (never {@code null})
  13. * @throws IOException in case of I/O failure
  14. */
  15. MetadataReader getMetadataReader(Resource resource) throws IOException;
  16. }
  • 接口解释的差不多了.接下来看一些实现

StandardClassMetadata

  • 通过 JAVA 反射来获取类的元信息

  • 这个类采用的方式是 Java class 的方法,通过构造方法来填写一个 Class 对象. 之后使用这个对象的方法

  1. public class StandardClassMetadata implements ClassMetadata {
  2. private final Class<?> introspectedClass;
  3. @Deprecated
  4. public StandardClassMetadata(Class<?> introspectedClass) {
  5. Assert.notNull(introspectedClass, "Class must not be null");
  6. this.introspectedClass = introspectedClass;
  7. }
  8. /**
  9. * Return the underlying Class.
  10. */
  11. public final Class<?> getIntrospectedClass() {
  12. return this.introspectedClass;
  13. }
  14. @Override
  15. public String getClassName() {
  16. return this.introspectedClass.getName();
  17. }
  18. @Override
  19. public boolean isInterface() {
  20. return this.introspectedClass.isInterface();
  21. }
  22. @Override
  23. public boolean isAnnotation() {
  24. return this.introspectedClass.isAnnotation();
  25. }
  26. @Override
  27. public boolean isAbstract() {
  28. return Modifier.isAbstract(this.introspectedClass.getModifiers());
  29. }
  30. @Override
  31. public boolean isFinal() {
  32. return Modifier.isFinal(this.introspectedClass.getModifiers());
  33. }
  34. @Override
  35. public boolean isIndependent() {
  36. return (!hasEnclosingClass() ||
  37. (this.introspectedClass.getDeclaringClass() != null &&
  38. Modifier.isStatic(this.introspectedClass.getModifiers())));
  39. }
  40. @Override
  41. @Nullable
  42. public String getEnclosingClassName() {
  43. Class<?> enclosingClass = this.introspectedClass.getEnclosingClass();
  44. return (enclosingClass != null ? enclosingClass.getName() : null);
  45. }
  46. @Override
  47. @Nullable
  48. public String getSuperClassName() {
  49. Class<?> superClass = this.introspectedClass.getSuperclass();
  50. return (superClass != null ? superClass.getName() : null);
  51. }
  52. @Override
  53. public String[] getInterfaceNames() {
  54. Class<?>[] ifcs = this.introspectedClass.getInterfaces();
  55. String[] ifcNames = new String[ifcs.length];
  56. for (int i = 0; i < ifcs.length; i++) {
  57. ifcNames[i] = ifcs[i].getName();
  58. }
  59. return ifcNames;
  60. }
  61. @Override
  62. public String[] getMemberClassNames() {
  63. LinkedHashSet<String> memberClassNames = new LinkedHashSet<>(4);
  64. for (Class<?> nestedClass : this.introspectedClass.getDeclaredClasses()) {
  65. memberClassNames.add(nestedClass.getName());
  66. }
  67. return StringUtils.toStringArray(memberClassNames);
  68. }
  69. }

StandardMethodMetadata

  • 通过 java 反射获取方法的元信息
  • 构造方法传递一个 method
    • 如果这个方法有注解,会进行注解的解析
  1. public class StandardMethodMetadata implements MethodMetadata {
  2. private final Method introspectedMethod;
  3. private final boolean nestedAnnotationsAsMap;
  4. private final MergedAnnotations mergedAnnotations;
  5. @Deprecated
  6. public StandardMethodMetadata(Method introspectedMethod) {
  7. this(introspectedMethod, false);
  8. }
  9. @Deprecated
  10. public StandardMethodMetadata(Method introspectedMethod, boolean nestedAnnotationsAsMap) {
  11. Assert.notNull(introspectedMethod, "Method must not be null");
  12. this.introspectedMethod = introspectedMethod;
  13. this.nestedAnnotationsAsMap = nestedAnnotationsAsMap;
  14. this.mergedAnnotations = MergedAnnotations.from(
  15. introspectedMethod, SearchStrategy.DIRECT, RepeatableContainers.none());
  16. }
  17. @Override
  18. public MergedAnnotations getAnnotations() {
  19. return this.mergedAnnotations;
  20. }
  21. /**
  22. * Return the underlying Method.
  23. */
  24. public final Method getIntrospectedMethod() {
  25. return this.introspectedMethod;
  26. }
  27. @Override
  28. public String getMethodName() {
  29. return this.introspectedMethod.getName();
  30. }
  31. @Override
  32. public String getDeclaringClassName() {
  33. return this.introspectedMethod.getDeclaringClass().getName();
  34. }
  35. @Override
  36. public String getReturnTypeName() {
  37. return this.introspectedMethod.getReturnType().getName();
  38. }
  39. @Override
  40. public boolean isAbstract() {
  41. return Modifier.isAbstract(this.introspectedMethod.getModifiers());
  42. }
  43. @Override
  44. public boolean isStatic() {
  45. return Modifier.isStatic(this.introspectedMethod.getModifiers());
  46. }
  47. @Override
  48. public boolean isFinal() {
  49. return Modifier.isFinal(this.introspectedMethod.getModifiers());
  50. }
  51. @Override
  52. public boolean isOverridable() {
  53. return !isStatic() && !isFinal() && !isPrivate();
  54. }
  55. private boolean isPrivate() {
  56. return Modifier.isPrivate(this.introspectedMethod.getModifiers());
  57. }
  58. @Override
  59. @Nullable
  60. public Map<String, Object> getAnnotationAttributes(String annotationName, boolean classValuesAsString) {
  61. if (this.nestedAnnotationsAsMap) {
  62. return MethodMetadata.super.getAnnotationAttributes(annotationName, classValuesAsString);
  63. }
  64. return AnnotatedElementUtils.getMergedAnnotationAttributes(this.introspectedMethod,
  65. annotationName, classValuesAsString, false);
  66. }
  67. /**
  68. * 获取所有注解的信息
  69. */
  70. @Override
  71. @Nullable
  72. public MultiValueMap<String, Object> getAllAnnotationAttributes(String annotationName, boolean classValuesAsString) {
  73. if (this.nestedAnnotationsAsMap) {
  74. return MethodMetadata.super.getAllAnnotationAttributes(annotationName, classValuesAsString);
  75. }
  76. return AnnotatedElementUtils.getAllAnnotationAttributes(this.introspectedMethod,
  77. annotationName, classValuesAsString, false);
  78. }
  79. }

StandardAnnotationMetadata

  • StandardAnnotationMetadata 是 StandardClassMetadata 的子类

  • 还是一个基于 JAVA 反射做的一个类

  • 获取注解属性 map

  1. @Override
  2. @Nullable
  3. public Map<String, Object> getAnnotationAttributes(String annotationName, boolean classValuesAsString) {
  4. if (this.nestedAnnotationsAsMap) {
  5. return AnnotationMetadata.super.getAnnotationAttributes(annotationName, classValuesAsString);
  6. }
  7. return AnnotatedElementUtils.getMergedAnnotationAttributes(
  8. getIntrospectedClass(), annotationName, classValuesAsString, false);
  9. }
  • org.springframework.core.annotation.AnnotatedElementUtils#getMergedAnnotationAttributes(java.lang.reflect.AnnotatedElement, java.lang.String, boolean, boolean)
    • org.springframework.core.annotation.AnnotatedElementUtils#getAnnotationAttributes
      • org.springframework.core.annotation.MergedAnnotation#asAnnotationAttributes
  1. @Nullable
  2. public static AnnotationAttributes getMergedAnnotationAttributes(AnnotatedElement element,
  3. String annotationName, boolean classValuesAsString, boolean nestedAnnotationsAsMap) {
  4. MergedAnnotation<?> mergedAnnotation = getAnnotations(element)
  5. .get(annotationName, null, MergedAnnotationSelectors.firstDirectlyDeclared());
  6. return getAnnotationAttributes(mergedAnnotation, classValuesAsString, nestedAnnotationsAsMap);
  7. }
  • 查看这个方法的源码借助测试类org.springframework.core.annotation.AnnotatedElementUtilsTests#getMergedAnnotationAttributesOnClassWithLocalAnnotation
  • getAnnotations() 方法

getAnnotations

  • org.springframework.core.annotation.MergedAnnotations#from(java.lang.reflect.AnnotatedElement, org.springframework.core.annotation.MergedAnnotations.SearchStrategy, org.springframework.core.annotation.RepeatableContainers)

    • org.springframework.core.annotation.TypeMappedAnnotations#from(java.lang.reflect.AnnotatedElement, org.springframework.core.annotation.MergedAnnotations.SearchStrategy, org.springframework.core.annotation.RepeatableContainers, org.springframework.core.annotation.AnnotationFilter)
  • 最终我们找到的代码如下

  1. static MergedAnnotations from(AnnotatedElement element, SearchStrategy searchStrategy,
  2. RepeatableContainers repeatableContainers, AnnotationFilter annotationFilter) {
  3. if (AnnotationsScanner.isKnownEmpty(element, searchStrategy)) {
  4. return NONE;
  5. }
  6. return new TypeMappedAnnotations(element, searchStrategy, repeatableContainers, annotationFilter);
  7. }
  • 判断是否为空. 为空返回 None,不会为空构造出一个对象 org.springframework.core.annotation.TypeMappedAnnotations

MergedAnnotations

  1. public interface MergedAnnotations extends Iterable<MergedAnnotation<Annotation>> {
  2. //确定注解是否存在
  3. <A extends Annotation> boolean isPresent(Class<A> annotationType);
  4. //注解是否直接存在
  5. <A extends Annotation> boolean isDirectlyPresent(Class<A> annotationType);
  6. // 获取匹配的注解
  7. <A extends Annotation> MergedAnnotation<A> get(Class<A> annotationType);
  8. // 省略其他
  9. }
  • 这个接口中还有两个方法

    1. of 将多个MergedAnnotations合并

    2. from

      将多个注解合并

SearchStrategy

  1. enum SearchStrategy {
  2. /**
  3. * Find only directly declared annotations, without considering
  4. * {@link Inherited @Inherited} annotations and without searching
  5. * superclasses or implemented interfaces.
  6. *
  7. * 直接查找
  8. */
  9. DIRECT,
  10. /**
  11. * Find all directly declared annotations as well as any
  12. * {@link Inherited @Inherited} superclass annotations. This strategy
  13. * is only really useful when used with {@link Class} types since the
  14. * {@link Inherited @Inherited} annotation is ignored for all other
  15. * {@linkplain AnnotatedElement annotated elements}. This strategy does
  16. * not search implemented interfaces.
  17. *
  18. * 继承查找
  19. */
  20. INHERITED_ANNOTATIONS,
  21. /**
  22. * Find all directly declared and superclass annotations. This strategy
  23. * is similar to {@link #INHERITED_ANNOTATIONS} except the annotations
  24. * do not need to be meta-annotated with {@link Inherited @Inherited}.
  25. * This strategy does not search implemented interfaces.
  26. * 查找当前类和父类的注解
  27. */
  28. SUPERCLASS,
  29. /**
  30. * Perform a full search of the entire type hierarchy, including
  31. * superclasses and implemented interfaces. Superclass annotations do
  32. * not need to be meta-annotated with {@link Inherited @Inherited}.
  33. */
  34. TYPE_HIERARCHY,
  35. /**
  36. * Perform a full search of the entire type hierarchy on the source
  37. * <em>and</em> any enclosing classes. This strategy is similar to
  38. * {@link #TYPE_HIERARCHY} except that {@linkplain Class#getEnclosingClass()
  39. * enclosing classes} are also searched. Superclass annotations do not
  40. * need to be meta-annotated with {@link Inherited @Inherited}. When
  41. * searching a {@link Method} source, this strategy is identical to
  42. * {@link #TYPE_HIERARCHY}.
  43. */
  44. TYPE_HIERARCHY_AND_ENCLOSING_CLASSES
  45. }
  • org.springframework.core.annotation.TypeMappedAnnotations#get(java.lang.String, java.util.function.Predicate<? super org.springframework.core.annotation.MergedAnnotation<A>>, org.springframework.core.annotation.MergedAnnotationSelector<A>)
  1. @Override
  2. public <A extends Annotation> MergedAnnotation<A> get(String annotationType,
  3. @Nullable Predicate<? super MergedAnnotation<A>> predicate,
  4. @Nullable MergedAnnotationSelector<A> selector) {
  5. // 匹配校验
  6. if (this.annotationFilter.matches(annotationType)) {
  7. return MergedAnnotation.missing();
  8. }
  9. MergedAnnotation<A> result = scan(annotationType,
  10. new MergedAnnotationFinder<>(annotationType, predicate, selector));
  11. return (result != null ? result : MergedAnnotation.missing());
  12. }

Scan

org.springframework.core.annotation.AnnotationsScanner#scan(C, java.lang.reflect.AnnotatedElement, org.springframework.core.annotation.MergedAnnotations.SearchStrategy, org.springframework.core.annotation.AnnotationsProcessor<C,R>, java.util.function.BiPredicate<C,java.lang.Class<?>>)

  1. @Nullable
  2. static <C, R> R scan(C context, AnnotatedElement source, SearchStrategy searchStrategy,
  3. AnnotationsProcessor<C, R> processor, @Nullable BiPredicate<C, Class<?>> classFilter) {
  4. R result = process(context, source, searchStrategy, processor, classFilter);
  5. return processor.finish(result);
  6. }

在这个里面重点关注PROCESS方法

  1. @Nullable
  2. private static <C, R> R process(C context, AnnotatedElement source,
  3. SearchStrategy searchStrategy, AnnotationsProcessor<C, R> processor,
  4. @Nullable BiPredicate<C, Class<?>> classFilter) {
  5. if (source instanceof Class) {
  6. return processClass(context, (Class<?>) source, searchStrategy, processor, classFilter);
  7. }
  8. if (source instanceof Method) {
  9. return processMethod(context, (Method) source, searchStrategy, processor, classFilter);
  10. }
  11. return processElement(context, source, processor, classFilter);
  12. }

测试类

  1. @Transactional("TxConfig")
  2. static class TxConfig {
  3. }

显然这是一个类他会走processClass方法

  • 根据扫描方式进行扫描
  1. @Nullable
  2. private static <C, R> R processClass(C context, Class<?> source,
  3. SearchStrategy searchStrategy, AnnotationsProcessor<C, R> processor,
  4. @Nullable BiPredicate<C, Class<?>> classFilter) {
  5. switch (searchStrategy) {
  6. case DIRECT:
  7. return processElement(context, source, processor, classFilter);
  8. case INHERITED_ANNOTATIONS:
  9. return processClassInheritedAnnotations(context, source, searchStrategy, processor, classFilter);
  10. case SUPERCLASS:
  11. return processClassHierarchy(context, source, processor, classFilter, false, false);
  12. case TYPE_HIERARCHY:
  13. return processClassHierarchy(context, source, processor, classFilter, true, false);
  14. case TYPE_HIERARCHY_AND_ENCLOSING_CLASSES:
  15. return processClassHierarchy(context, source, processor, classFilter, true, true);
  16. }
  17. throw new IllegalStateException("Unsupported search strategy " + searchStrategy);
  18. }
  • 扫描的形式就不贴出完整代码了

finish就包装一下返回.

  • 此时org.springframework.core.annotation.AnnotatedElementUtils#getMergedAnnotationAttributes(java.lang.reflect.AnnotatedElement, java.lang.String, boolean, boolean)这个方法走到了最后一步org.springframework.core.annotation.AnnotatedElementUtils#getAnnotationAttributes

  • 最后的组装 map 方法

    org.springframework.core.annotation.TypeMappedAnnotation#asMap(java.util.function.Function<org.springframework.core.annotation.MergedAnnotation<?>,T>, org.springframework.core.annotation.MergedAnnotation.Adapt...)

  1. @Override
  2. public AnnotationAttributes asAnnotationAttributes(Adapt... adaptations) {
  3. return asMap(mergedAnnotation -> new AnnotationAttributes(mergedAnnotation.getType()), adaptations);
  4. }
  1. @Override
  2. public <T extends Map<String, Object>> T asMap(Function<MergedAnnotation<?>, T> factory, Adapt... adaptations) {
  3. T map = factory.apply(this);
  4. Assert.state(map != null, "Factory used to create MergedAnnotation Map must not return null");
  5. AttributeMethods attributes = this.mapping.getAttributes();
  6. for (int i = 0; i < attributes.size(); i++) {
  7. Method attribute = attributes.get(i);
  8. Object value = (isFiltered(attribute.getName()) ? null :
  9. getValue(i, getTypeForMapOptions(attribute, adaptations)));
  10. if (value != null) {
  11. map.put(attribute.getName(),
  12. adaptValueForMapOptions(attribute, value, map.getClass(), factory, adaptations));
  13. }
  14. }
  15. return map;
  16. }
  • 获取属性列表,循环, 放入 map 返回.

    map

    ​ key: 注解的函数

    ​ value: 函数对应的值

  1. @Transactional("TxConfig")
  1. @Retention(RetentionPolicy.RUNTIME)
  2. @Target({ElementType.TYPE, ElementType.METHOD})
  3. @Inherited
  4. @interface Transactional {
  5. String value() default "";
  6. String qualifier() default "transactionManager";
  7. boolean readOnly() default false;
  8. }

如果是上面这样的结构那么返回值为

  1. value:TxConfig
  2. qulifiter:transactionManager
  3. readOnlay:false

image-20200824104529315

SimpleMetadataReader

  • 构造方法传递三个参数直接使用

    ```java final class SimpleMetadataReader implements MetadataReader {

    private static final int PARSING_OPTIONS = ClassReader.SKIP_DEBUG

    1. | ClassReader.SKIP_CODE | ClassReader.SKIP_FRAMES;

    private final Resource resource;

    private final AnnotationMetadata annotationMetadata;

  1. SimpleMetadataReader(Resource resource, @Nullable ClassLoader classLoader) throws IOException {
  2. SimpleAnnotationMetadataReadingVisitor visitor = new SimpleAnnotationMetadataReadingVisitor(classLoader);
  3. getClassReader(resource).accept(visitor, PARSING_OPTIONS);
  4. this.resource = resource;
  5. this.annotationMetadata = visitor.getMetadata();
  6. }
  7. private static ClassReader getClassReader(Resource resource) throws IOException {
  8. try (InputStream is = new BufferedInputStream(resource.getInputStream())) {
  9. try {
  10. return new ClassReader(is);
  11. }
  12. catch (IllegalArgumentException ex) {
  13. throw new NestedIOException("ASM ClassReader failed to parse class file - " +
  14. "probably due to a new Java class file version that isn't supported yet: " + resource, ex);
  15. }
  16. }
  17. }
  18. @Override
  19. public Resource getResource() {
  20. return this.resource;
  21. }
  22. @Override
  23. public ClassMetadata getClassMetadata() {
  24. return this.annotationMetadata;
  25. }
  26. @Override
  27. public AnnotationMetadata getAnnotationMetadata() {
  28. return this.annotationMetadata;
  29. }

}

  1. ## SimpleMetadataReaderFactory
  2. - 关注点为如何获取`MetadataReader`
  3. 1. 通过资源直接 new 出来
  4. 2. 通过 className 转换成资源地址,
  5. 3. 将资源地址转换成`Resource`对象
  6. 4. new 出来
  7. ```java
  8. @Override
  9. public MetadataReader getMetadataReader(String className) throws IOException {
  10. try {
  11. String resourcePath = ResourceLoader.CLASSPATH_URL_PREFIX +
  12. ClassUtils.convertClassNameToResourcePath(className) + ClassUtils.CLASS_FILE_SUFFIX;
  13. Resource resource = this.resourceLoader.getResource(resourcePath);
  14. return getMetadataReader(resource);
  15. }
  16. catch (FileNotFoundException ex) {
  17. // Maybe an inner class name using the dot name syntax? Need to use the dollar syntax here...
  18. // ClassUtils.forName has an equivalent check for resolution into Class references later on.
  19. int lastDotIndex = className.lastIndexOf('.');
  20. if (lastDotIndex != -1) {
  21. String innerClassName =
  22. className.substring(0, lastDotIndex) + '$' + className.substring(lastDotIndex + 1);
  23. String innerClassResourcePath = ResourceLoader.CLASSPATH_URL_PREFIX +
  24. ClassUtils.convertClassNameToResourcePath(innerClassName) + ClassUtils.CLASS_FILE_SUFFIX;
  25. Resource innerClassResource = this.resourceLoader.getResource(innerClassResourcePath);
  26. if (innerClassResource.exists()) {
  27. return getMetadataReader(innerClassResource);
  28. }
  29. }
  30. throw ex;
  31. }
  32. }
  33. @Override
  34. public MetadataReader getMetadataReader(Resource resource) throws IOException {
  35. return new SimpleMetadataReader(resource, this.resourceLoader.getClassLoader());
  36. }