Spring 源码解析四:Bean 的构造装载、属性值解析、注解扫描

x33g5p2x  于2022-02-11 发布在 Spring  
字(23.9k)|赞(0)|评价(0)|浏览(614)

上一篇主要介绍了 Bean 的注册、解析、实例化,但留下一些点待解析:

  • ConstructorResolver.autowireConstructor 如何进行构造装载并实例化的
  • CglibSubclassingInstantiationStrategy.instantiate 如何动态实例化 bean 的
  • BeanDefinitionValueResolver.resolveValueIfNecessary 如何解析属性值的
  • MergedAnnotations.from 如何扫描注解的

这一节,就来解析这几个点

1. ConstructorResolver.autowireConstructor

ConstructorResolver
的主要功能是在构造时载入依赖的 bean 和用 factory-method 实例化 bean,这里只讲第一个:在构造时载入依赖的 bean ConstructorResolver.autowireConstructor

  1. class ConstructorResolver {
  2. public BeanWrapper autowireConstructor(String beanName, RootBeanDefinition mbd,
  3. @Nullable Constructor<?>[] chosenCtors, @Nullable Object[] explicitArgs) {
  4. // 实例化一个封装对象
  5. BeanWrapperImpl bw = new BeanWrapperImpl();
  6. // 需要使用的构造方法
  7. Constructor<?> constructorToUse = null;
  8. // 需要使用的构造参数
  9. Object[] argsToUse = null;
  10. // 如果指定了参数,就使用指定的参数
  11. if (explicitArgs != null) {
  12. argsToUse = explicitArgs;
  13. }
  14. else {
  15. Object[] argsToResolve = null;
  16. // 并发处理
  17. synchronized (mbd.constructorArgumentLock) {
  18. // 获取定义中已解析的构造方法
  19. constructorToUse = (Constructor<?>) mbd.resolvedConstructorOrFactoryMethod;
  20. if (constructorToUse != null && mbd.constructorArgumentsResolved) {
  21. // 获取定义中已解析的参数,首先是resolvedConstructorArguments,其次是preparedConstructorArguments
  22. argsToUse = mbd.resolvedConstructorArguments;
  23. if (argsToUse == null) {
  24. argsToResolve = mbd.preparedConstructorArguments;
  25. }
  26. }
  27. }
  28. if (argsToResolve != null) {
  29. // 把参数解析成实际要用的数据,如bean装配、属性载入
  30. argsToUse = resolvePreparedArguments(beanName, mbd, bw, constructorToUse, argsToResolve);
  31. }
  32. }
  33. // 如果没有指定的构造方法或参数
  34. if (constructorToUse == null || argsToUse == null) {
  35. Constructor<?>[] candidates = chosenCtors;
  36. if (candidates == null) {
  37. // 如果传入的chosenCtors是空,则获取beanClass的构造方法
  38. Class<?> beanClass = mbd.getBeanClass();
  39. try {
  40. candidates = (mbd.isNonPublicAccessAllowed() ?
  41. beanClass.getDeclaredConstructors() : beanClass.getConstructors());
  42. }
  43. catch (Throwable ex) {
  44. // ... 代码省略
  45. }
  46. }
  47. // 如果只有一个构造方法,并且没有指定explicitArgs和constructorArgumentValues
  48. if (candidates.length == 1 && explicitArgs == null && !mbd.hasConstructorArgumentValues()) {
  49. Constructor<?> uniqueCandidate = candidates[0];
  50. // 如果构造方法没有参数需要装配,直接实例化返回
  51. if (uniqueCandidate.getParameterCount() == 0) {
  52. synchronized (mbd.constructorArgumentLock) {
  53. mbd.resolvedConstructorOrFactoryMethod = uniqueCandidate;
  54. mbd.constructorArgumentsResolved = true;
  55. mbd.resolvedConstructorArguments = EMPTY_ARGS;
  56. }
  57. // 实例化bean
  58. bw.setBeanInstance(instantiate(beanName, mbd, uniqueCandidate, EMPTY_ARGS));
  59. return bw;
  60. }
  61. }
  62. // 有构造方法,且构造模式为AUTOWIRE_CONSTRUCTOR,则需要自动装配bean
  63. boolean autowiring = (chosenCtors != null ||
  64. mbd.getResolvedAutowireMode() == AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR);
  65. ConstructorArgumentValues resolvedValues = null;
  66. // ... 代码省略
  67. // 选择一个参数数量、参数类型、参数顺序与需要实例化参数对象最接近的一个构造方法
  68. // 这里的计算比较复杂,有兴趣的朋友可以自行探索一下
  69. for (Constructor<?> candidate : candidates) {
  70. // ... 代码省略
  71. }
  72. // ... 代码省略
  73. }
  74. // 实例化bean
  75. bw.setBeanInstance(instantiate(beanName, mbd, constructorToUse, argsToUse));
  76. return bw;
  77. }
  78. // 实例化bean,默认使用CglibSubclassingInstantiationStrategy.instantiate来实例化
  79. private Object instantiate(
  80. String beanName, RootBeanDefinition mbd, Constructor<?> constructorToUse, Object[] argsToUse) {
  81. try {
  82. InstantiationStrategy strategy = this.beanFactory.getInstantiationStrategy();
  83. if (System.getSecurityManager() != null) {
  84. return AccessController.doPrivileged((PrivilegedAction<Object>) () ->
  85. strategy.instantiate(mbd, beanName, this.beanFactory, constructorToUse, argsToUse),
  86. this.beanFactory.getAccessControlContext());
  87. }
  88. else {
  89. return strategy.instantiate(mbd, beanName, this.beanFactory, constructorToUse, argsToUse);
  90. }
  91. }
  92. catch (Throwable ex) {
  93. // ... 代码省略
  94. }
  95. }
  96. }

最终的实例化仍然需要CglibSubclassingInstantiationStrategy.instantiate来实现

2. CglibSubclassingInstantiationStrategy.instantiate

CglibSubclassingInstantiationStrategy
的主要功能是使用 cglib 的方式实例化 bean

  1. public class CglibSubclassingInstantiationStrategy extends SimpleInstantiationStrategy {}

我们先来看看 SimpleInstantiationStrategy

  1. public class SimpleInstantiationStrategy implements InstantiationStrategy {
  2. // 用于调用factory-method
  3. private static final ThreadLocal<Method> currentlyInvokedFactoryMethod = new ThreadLocal<>();
  4. @Override
  5. public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
  6. // 没有方法需要重载
  7. if (!bd.hasMethodOverrides()) {
  8. Constructor<?> constructorToUse;
  9. synchronized (bd.constructorArgumentLock) {
  10. // 首先获取已解析的构造方法
  11. constructorToUse = (Constructor<?>) bd.resolvedConstructorOrFactoryMethod;
  12. if (constructorToUse == null) {
  13. // 没有已解析的构造方法,则用beanClass获取
  14. final Class<?> clazz = bd.getBeanClass();
  15. // 接口不能实例化
  16. if (clazz.isInterface()) {
  17. throw new BeanInstantiationException(clazz, "Specified class is an interface");
  18. }
  19. try {
  20. if (System.getSecurityManager() != null) {
  21. constructorToUse = AccessController.doPrivileged(
  22. (PrivilegedExceptionAction<Constructor<?>>) clazz::getDeclaredConstructor);
  23. }
  24. else {
  25. // 通过Class获取构造方法
  26. constructorToUse = clazz.getDeclaredConstructor();
  27. }
  28. // 设为已解析的构造方法
  29. bd.resolvedConstructorOrFactoryMethod = constructorToUse;
  30. }
  31. catch (Throwable ex) {
  32. // 如果Class没有构造方法,报错
  33. }
  34. }
  35. }
  36. // 调用Constructor..newInstance实例化
  37. return BeanUtils.instantiateClass(constructorToUse);
  38. }
  39. else {
  40. // 有方法需要重载,则需要用cglib生成一个新的子类
  41. return instantiateWithMethodInjection(bd, beanName, owner);
  42. }
  43. }
  44. // 方法注入实例化,留给子类实现
  45. protected Object instantiateWithMethodInjection(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
  46. throw new UnsupportedOperationException("Method Injection not supported in SimpleInstantiationStrategy");
  47. }
  48. @Override
  49. public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner,
  50. final Constructor<?> ctor, Object... args) {
  51. // 没有方法需要重载
  52. if (!bd.hasMethodOverrides()) {
  53. // ... 代码省略
  54. // 调用Constructor.newInstance实例化
  55. return BeanUtils.instantiateClass(ctor, args);
  56. }
  57. else {
  58. // 有方法需要重载,则需要用cglib生成一个新的子类
  59. return instantiateWithMethodInjection(bd, beanName, owner, ctor, args);
  60. }
  61. }
  62. // 方法注入实例化,留给子类实现
  63. protected Object instantiateWithMethodInjection(RootBeanDefinition bd, @Nullable String beanName,
  64. BeanFactory owner, @Nullable Constructor<?> ctor, Object... args) {
  65. throw new UnsupportedOperationException("Method Injection not supported in SimpleInstantiationStrategy");
  66. }
  67. // 通过factory-method初始化
  68. @Override
  69. public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner,
  70. @Nullable Object factoryBean, final Method factoryMethod, Object... args) {
  71. try {
  72. // ... 代码省略
  73. // 直接调用Method.invoke实例化
  74. Object result = factoryMethod.invoke(factoryBean, args);
  75. // 如果为null,实例化一个NullBean
  76. if (result == null) {
  77. result = new NullBean();
  78. }
  79. return result;
  80. }
  81. catch (IllegalArgumentException ex) {
  82. // ... 代码省略
  83. }
  84. catch (IllegalAccessException ex) {
  85. // ... 代码省略
  86. }
  87. catch (InvocationTargetException ex) {
  88. // ... 代码省略
  89. }
  90. }
  91. }

我们先来看看 CglibSubclassingInstantiationStrategy

  1. public class CglibSubclassingInstantiationStrategy extends SimpleInstantiationStrategy {
  2. @Override
  3. protected Object instantiateWithMethodInjection(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
  4. return instantiateWithMethodInjection(bd, beanName, owner, null);
  5. }
  6. @Override
  7. protected Object instantiateWithMethodInjection(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner,
  8. @Nullable Constructor<?> ctor, Object... args) {
  9. // 生成一个CglibSubclassCreator来实例化
  10. return new CglibSubclassCreator(bd, owner).instantiate(ctor, args);
  11. }
  12. }

CglibSubclassCreatorCglibSubclassingInstantiationStrategy的内部类

  1. private static class CglibSubclassCreator {
  2. // 实例化一个构造函数
  3. public Object instantiate(@Nullable Constructor<?> ctor, Object... args) {
  4. // 使用cglib Enhancer创建一个加强子类
  5. Class<?> subclass = createEnhancedSubclass(this.beanDefinition);
  6. Object instance;
  7. if (ctor == null) {
  8. // 如果没有指定构造函数,调用Constructor.newInstance实例化
  9. instance = BeanUtils.instantiateClass(subclass);
  10. }
  11. else {
  12. try {
  13. // 获取与ctor参数匹配的子类构造函数,再调用Constructor.newInstance实例化
  14. Constructor<?> enhancedSubclassConstructor = subclass.getConstructor(ctor.getParameterTypes());
  15. instance = enhancedSubclassConstructor.newInstance(args);
  16. }
  17. catch (Exception ex) {
  18. // ... 代码省略
  19. }
  20. }
  21. // ... 代码省略
  22. return instance;
  23. }
  24. // 使用cglib Enhancer创建一个加强子类
  25. private Class<?> createEnhancedSubclass(RootBeanDefinition beanDefinition) {
  26. Enhancer enhancer = new Enhancer();
  27. enhancer.setSuperclass(beanDefinition.getBeanClass());
  28. enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
  29. if (this.owner instanceof ConfigurableBeanFactory) {
  30. ClassLoader cl = ((ConfigurableBeanFactory) this.owner).getBeanClassLoader();
  31. enhancer.setStrategy(new ClassLoaderAwareGeneratorStrategy(cl));
  32. }
  33. enhancer.setCallbackFilter(new MethodOverrideCallbackFilter(beanDefinition));
  34. enhancer.setCallbackTypes(CALLBACK_TYPES);
  35. return enhancer.createClass();
  36. }
  37. }

3. BeanDefinitionValueResolver.resolveValueIfNecessary

BeanDefinitionValueResolver
的主要功能是将配置的属性值装载到 bean 中

  1. class BeanDefinitionValueResolver {
  2. public Object resolveValueIfNecessary(Object argName, @Nullable Object value) {
  3. // 在运行时对其他bean的引用
  4. if (value instanceof RuntimeBeanReference) {
  5. RuntimeBeanReference ref = (RuntimeBeanReference) value;
  6. // 解析引用bean
  7. return resolveReference(argName, ref);
  8. }
  9. // 在运行时对其他bean name的引用
  10. else if (value instanceof RuntimeBeanNameReference) {
  11. String refName = ((RuntimeBeanNameReference) value).getBeanName();
  12. // 使用doEvaluate解析bean名字,执行SpEL表达式
  13. refName = String.valueOf(doEvaluate(refName));
  14. if (!this.beanFactory.containsBean(refName)) {
  15. // 没注册过bean name,报错
  16. }
  17. return refName;
  18. }
  19. // 包含别名的bean定义
  20. else if (value instanceof BeanDefinitionHolder) {
  21. BeanDefinitionHolder bdHolder = (BeanDefinitionHolder) value;
  22. // 解析内部bean
  23. return resolveInnerBean(argName, bdHolder.getBeanName(), bdHolder.getBeanDefinition());
  24. }
  25. // bean定义
  26. else if (value instanceof BeanDefinition) {
  27. BeanDefinition bd = (BeanDefinition) value;
  28. // 内部bean名字
  29. String innerBeanName = "(inner bean)" + BeanFactoryUtils.GENERATED_BEAN_NAME_SEPARATOR +
  30. ObjectUtils.getIdentityHexString(bd);
  31. // 解析内部bean
  32. return resolveInnerBean(argName, innerBeanName, bd);
  33. }
  34. // 注入依赖描述(类、方法、属性)
  35. else if (value instanceof DependencyDescriptor) {
  36. Set<String> autowiredBeanNames = new LinkedHashSet<>(4);
  37. // 解析依赖
  38. Object result = this.beanFactory.resolveDependency(
  39. (DependencyDescriptor) value, this.beanName, autowiredBeanNames, this.typeConverter);
  40. for (String autowiredBeanName : autowiredBeanNames) {
  41. if (this.beanFactory.containsBean(autowiredBeanName)) {
  42. // 注册依赖
  43. this.beanFactory.registerDependentBean(autowiredBeanName, this.beanName);
  44. }
  45. }
  46. return result;
  47. }
  48. // ... 代码省略
  49. // 是字符类型的值
  50. else if (value instanceof TypedStringValue) {
  51. TypedStringValue typedStringValue = (TypedStringValue) value;
  52. // 使用evaluate解析bean名字,执行SpEL表达式
  53. Object valueObject = evaluate(typedStringValue);
  54. try {
  55. // 解析类型
  56. Class<?> resolvedTargetType = resolveTargetType(typedStringValue);
  57. // 如果有类型,把valueObject转换成这个类型
  58. if (resolvedTargetType != null) {
  59. return this.typeConverter.convertIfNecessary(valueObject, resolvedTargetType);
  60. }
  61. // 没有指定类型,则返回原本的
  62. else {
  63. return valueObject;
  64. }
  65. }
  66. catch (Throwable ex) {
  67. // ... 代码省略
  68. }
  69. }
  70. // 如果是NullBean,返回null
  71. else if (value instanceof NullBean) {
  72. return null;
  73. }
  74. // 默认当成SpEL表达式解析了
  75. else {
  76. return evaluate(value);
  77. }
  78. }
  79. }

BeanDefinitionValueResolver.resolveReference
解析引用 bean

  1. class BeanDefinitionValueResolver {
  2. private Object resolveReference(Object argName, RuntimeBeanReference ref) {
  3. try {
  4. Object bean;
  5. // 获取bean类型
  6. Class<?> beanType = ref.getBeanType();
  7. if (ref.isToParent()) {
  8. // 指明从父BeanFactory中获取
  9. BeanFactory parent = this.beanFactory.getParentBeanFactory();
  10. if (beanType != null) {
  11. // 如果有beanType,直接通过类型获取bean
  12. bean = parent.getBean(beanType);
  13. }
  14. else {
  15. // 使用doEvaluate解析bean名字,执行SpEL表达式,然后根据名字查找bean
  16. bean = parent.getBean(String.valueOf(doEvaluate(ref.getBeanName())));
  17. }
  18. }
  19. else {
  20. String resolvedName;
  21. if (beanType != null) {
  22. // 如果有beanType,直接通过类型获取bean
  23. NamedBeanHolder<?> namedBean = this.beanFactory.resolveNamedBean(beanType);
  24. bean = namedBean.getBeanInstance();
  25. resolvedName = namedBean.getBeanName();
  26. }
  27. else {
  28. // 使用doEvaluate解析bean名字,执行SpEL表达式,然后根据名字查找bean
  29. resolvedName = String.valueOf(doEvaluate(ref.getBeanName()));
  30. bean = this.beanFactory.getBean(resolvedName);
  31. }
  32. // 注册依赖
  33. this.beanFactory.registerDependentBean(resolvedName, this.beanName);
  34. }
  35. // 如果是NullBean,返回null
  36. if (bean instanceof NullBean) {
  37. bean = null;
  38. }
  39. return bean;
  40. }
  41. catch (BeansException ex) {
  42. // ... 代码省略
  43. }
  44. }
  45. // 调用beanFactory来解析bean名字,执行SpEL表达式
  46. private Object doEvaluate(String value) {
  47. return this.beanFactory.evaluateBeanDefinitionString(value, this.beanDefinition);
  48. }
  49. }

BeanDefinitionValueResolver.resolveInnerBean
解析内部 bean

  1. class BeanDefinitionValueResolver {
  2. private Object resolveInnerBean(Object argName, String innerBeanName, BeanDefinition innerBd) {
  3. RootBeanDefinition mbd = null;
  4. try {
  5. // 获取合并父bean定义的bean定义
  6. mbd = this.beanFactory.getMergedBeanDefinition(innerBeanName, innerBd, this.beanDefinition);
  7. String actualInnerBeanName = innerBeanName;
  8. if (mbd.isSingleton()) {
  9. // 如果同类型的bean被实例化多次,则使用后缀#1,#2...来命名之后的bean
  10. actualInnerBeanName = adaptInnerBeanName(innerBeanName);
  11. }
  12. // 把新生成的名字注册到beanFactory
  13. this.beanFactory.registerContainedBean(actualInnerBeanName, this.beanName);
  14. // 获取依赖
  15. String[] dependsOn = mbd.getDependsOn();
  16. if (dependsOn != null) {
  17. for (String dependsOnBean : dependsOn) {
  18. // 注册依赖
  19. this.beanFactory.registerDependentBean(dependsOnBean, actualInnerBeanName);
  20. // 确保加载
  21. this.beanFactory.getBean(dependsOnBean);
  22. }
  23. }
  24. // 创建bean
  25. Object innerBean = this.beanFactory.createBean(actualInnerBeanName, mbd, null);
  26. // 如果bean实例是FactoryBean,则调用factory-method获取真正的bean
  27. if (innerBean instanceof FactoryBean) {
  28. boolean synthetic = mbd.isSynthetic();
  29. innerBean = this.beanFactory.getObjectFromFactoryBean(
  30. (FactoryBean<?>) innerBean, actualInnerBeanName, !synthetic);
  31. }
  32. // 如果是NullBean,返回null
  33. if (innerBean instanceof NullBean) {
  34. innerBean = null;
  35. }
  36. return innerBean;
  37. }
  38. catch (BeansException ex) {
  39. // ... 代码省略
  40. }
  41. }
  42. // 如果同类型的bean被实例化多次,则使用后缀#1,#2...来命名之后的bean
  43. private String adaptInnerBeanName(String innerBeanName) {
  44. String actualInnerBeanName = innerBeanName;
  45. int counter = 0;
  46. String prefix = innerBeanName + BeanFactoryUtils.GENERATED_BEAN_NAME_SEPARATOR;
  47. while (this.beanFactory.isBeanNameInUse(actualInnerBeanName)) {
  48. counter++;
  49. actualInnerBeanName = prefix + counter;
  50. }
  51. return actualInnerBeanName;
  52. }
  53. }

4. MergedAnnotations.from

MergedAnnotations.from
的底层实现其实是 TypeMappedAnnotations.from

TypeMappedAnnotations的主要功能就是搜索、操作注解

  1. final class TypeMappedAnnotations implements MergedAnnotations {
  2. static MergedAnnotations from(AnnotatedElement element, SearchStrategy searchStrategy,
  3. RepeatableContainers repeatableContainers, AnnotationFilter annotationFilter) {
  4. // 没有可用的注解,直接返回NONE
  5. if (AnnotationsScanner.isKnownEmpty(element, searchStrategy)) {
  6. return NONE;
  7. }
  8. return new TypeMappedAnnotations(element, searchStrategy, repeatableContainers, annotationFilter);
  9. }
  10. static MergedAnnotations from(@Nullable Object source, Annotation[] annotations,
  11. RepeatableContainers repeatableContainers, AnnotationFilter annotationFilter) {
  12. // 没有要查找的注解,直接返回NONE
  13. if (annotations.length == 0) {
  14. return NONE;
  15. }
  16. return new TypeMappedAnnotations(source, annotations, repeatableContainers, annotationFilter);
  17. }
  18. }
  1. final class TypeMappedAnnotations implements MergedAnnotations {
  2. // 检查是否有annotationType
  3. @Override
  4. public <A extends Annotation> boolean isPresent(Class<A> annotationType) {
  5. // 过滤器没通过,返回false
  6. if (this.annotationFilter.matches(annotationType)) {
  7. return false;
  8. }
  9. // 扫描目标元素(类、方法、属性)
  10. return Boolean.TRUE.equals(scan(annotationType,
  11. IsPresent.get(this.repeatableContainers, this.annotationFilter, false)));
  12. }
  13. // 检查是否有annotationType
  14. @Override
  15. public boolean isPresent(String annotationType) {
  16. // 过滤器没通过,返回false
  17. if (this.annotationFilter.matches(annotationType)) {
  18. return false;
  19. }
  20. // 扫描目标元素(类、方法、属性)
  21. return Boolean.TRUE.equals(scan(annotationType,
  22. IsPresent.get(this.repeatableContainers, this.annotationFilter, false)));
  23. }
  24. // 获取目标元素的annotationType注解对象
  25. @Override
  26. public <A extends Annotation> MergedAnnotation<A> get(Class<A> annotationType,
  27. @Nullable Predicate<? super MergedAnnotation<A>> predicate,
  28. @Nullable MergedAnnotationSelector<A> selector) {
  29. // 过滤器没通过,返回空
  30. if (this.annotationFilter.matches(annotationType)) {
  31. return MergedAnnotation.missing();
  32. }
  33. // 扫描目标元素(类、方法、属性)
  34. MergedAnnotation<A> result = scan(annotationType,
  35. new MergedAnnotationFinder<>(annotationType, predicate, selector));
  36. return (result != null ? result : MergedAnnotation.missing());
  37. }
  38. // 获取目标元素的annotationType注解对象
  39. @Override
  40. public <A extends Annotation> MergedAnnotation<A> get(String annotationType,
  41. @Nullable Predicate<? super MergedAnnotation<A>> predicate,
  42. @Nullable MergedAnnotationSelector<A> selector) {
  43. // 过滤器没通过,返回空
  44. if (this.annotationFilter.matches(annotationType)) {
  45. return MergedAnnotation.missing();
  46. }
  47. // 扫描目标元素(类、方法、属性)
  48. MergedAnnotation<A> result = scan(annotationType,
  49. new MergedAnnotationFinder<>(annotationType, predicate, selector));
  50. return (result != null ? result : MergedAnnotation.missing());
  51. }
  52. // 扫描目标元素(类、方法、属性)
  53. private <C, R> R scan(C criteria, AnnotationsProcessor<C, R> processor) {
  54. // 如果有传入的注解对象,就不扫描目标元素了
  55. if (this.annotations != null) {
  56. R result = processor.doWithAnnotations(criteria, 0, this.source, this.annotations);
  57. return processor.finish(result);
  58. }
  59. // 有目标元素和扫描策略,扫描目标元素
  60. if (this.element != null && this.searchStrategy != null) {
  61. return AnnotationsScanner.scan(criteria, this.element, this.searchStrategy, processor);
  62. }
  63. return null;
  64. }
  65. }

TypeMappedAnnotations.scan 的底层实现是 AnnotationsScanner.scan

  1. abstract class AnnotationsScanner {
  2. // 扫描注解
  3. static <C, R> R scan(C context, AnnotatedElement source, SearchStrategy searchStrategy,
  4. AnnotationsProcessor<C, R> processor) {
  5. // 实际扫描处理
  6. R result = process(context, source, searchStrategy, processor);
  7. return processor.finish(result);
  8. }
  9. // 实际扫描处理
  10. private static <C, R> R process(C context, AnnotatedElement source,
  11. SearchStrategy searchStrategy, AnnotationsProcessor<C, R> processor) {
  12. // 如果目标元素是类,按类处理
  13. if (source instanceof Class) {
  14. return processClass(context, (Class<?>) source, searchStrategy, processor);
  15. }
  16. // 如果目标元素是方法,按方法处理
  17. if (source instanceof Method) {
  18. return processMethod(context, (Method) source, searchStrategy, processor);
  19. }
  20. // 不然按普通处理
  21. return processElement(context, source, processor);
  22. }
  23. }

4.1. 按类处理

  1. abstract class AnnotationsScanner {
  2. private static <C, R> R processClass(C context, Class<?> source,
  3. SearchStrategy searchStrategy, AnnotationsProcessor<C, R> processor) {
  4. switch (searchStrategy) {
  5. // 只搜索自身的注解,按普通处理
  6. case DIRECT:
  7. return processElement(context, source, processor);
  8. // 搜索自身与标记为@Inherited父类的注解
  9. case INHERITED_ANNOTATIONS:
  10. return processClassInheritedAnnotations(context, source, searchStrategy, processor);
  11. // 搜索自身与父类的注解
  12. case SUPERCLASS:
  13. return processClassHierarchy(context, source, processor, false, false);
  14. // 搜索自身、父类、接口的注解
  15. case TYPE_HIERARCHY:
  16. return processClassHierarchy(context, source, processor, true, false);
  17. // 搜索自身、父类、接口、getEnclosingClass()的注解
  18. case TYPE_HIERARCHY_AND_ENCLOSING_CLASSES:
  19. return processClassHierarchy(context, source, processor, true, true);
  20. }
  21. throw new IllegalStateException("Unsupported search strategy " + searchStrategy);
  22. }
  23. // 搜索自身与标记为@Inherited父类的注解
  24. private static <C, R> R processClassInheritedAnnotations(C context, Class<?> source,
  25. SearchStrategy searchStrategy, AnnotationsProcessor<C, R> processor) {
  26. try {
  27. // 如果除了自身以外,没有父类、接口、getEnclosingClass()的注解,按普通处理
  28. if (isWithoutHierarchy(source, searchStrategy)) {
  29. return processElement(context, source, processor);
  30. }
  31. Annotation[] relevant = null;
  32. int remaining = Integer.MAX_VALUE;
  33. int aggregateIndex = 0;
  34. Class<?> root = source;
  35. // source对象还可以继续向父类上溯
  36. // 非Object,非Ordered,非"java."开头
  37. while (source != null && source != Object.class && remaining > 0 &&
  38. !hasPlainJavaAnnotationsOnly(source)) {
  39. // 聚合处理,如果有了,直接返回(默认未实现)
  40. R result = processor.doWithAggregate(context, aggregateIndex);
  41. if (result != null) {
  42. return result;
  43. }
  44. // 获取所有public的注解
  45. Annotation[] declaredAnnotations = getDeclaredAnnotations(source, true);
  46. // ... 代码省略
  47. // 处理器自定义处理
  48. result = processor.doWithAnnotations(context, aggregateIndex, source, declaredAnnotations);
  49. // 如果有了,返回
  50. if (result != null) {
  51. return result;
  52. }
  53. // 上溯父类,继续扫描
  54. source = source.getSuperclass();
  55. aggregateIndex++;
  56. }
  57. }
  58. catch (Throwable ex) {
  59. // ... 代码省略
  60. }
  61. return null;
  62. }
  63. // 搜索自身、父类、接口、getEnclosingClass()的注解
  64. private static <C, R> R processClassHierarchy(C context, int[] aggregateIndex, Class<?> source,
  65. AnnotationsProcessor<C, R> processor, boolean includeInterfaces, boolean includeEnclosing) {
  66. try {
  67. // 聚合处理,如果有了,直接返回(默认未实现)
  68. R result = processor.doWithAggregate(context, aggregateIndex[0]);
  69. if (result != null) {
  70. return result;
  71. }
  72. // 如果是Ordered或"java."开头,返回
  73. if (hasPlainJavaAnnotationsOnly(source)) {
  74. return null;
  75. }
  76. // 获取所有public的注解
  77. Annotation[] annotations = getDeclaredAnnotations(source, false);
  78. // 处理器自定义处理
  79. result = processor.doWithAnnotations(context, aggregateIndex[0], source, annotations);
  80. // 如果有了,返回
  81. if (result != null) {
  82. return result;
  83. }
  84. aggregateIndex[0]++;
  85. // 如果包括接口,继续搜索接口的
  86. if (includeInterfaces) {
  87. for (Class<?> interfaceType : source.getInterfaces()) {
  88. R interfacesResult = processClassHierarchy(context, aggregateIndex,
  89. interfaceType, processor, true, includeEnclosing);
  90. if (interfacesResult != null) {
  91. return interfacesResult;
  92. }
  93. }
  94. }
  95. // 如果有父类,继续搜索父类的
  96. Class<?> superclass = source.getSuperclass();
  97. if (superclass != Object.class && superclass != null) {
  98. R superclassResult = processClassHierarchy(context, aggregateIndex,
  99. superclass, processor, includeInterfaces, includeEnclosing);
  100. if (superclassResult != null) {
  101. return superclassResult;
  102. }
  103. }
  104. // 如果包括getEnclosingClass(),继续搜索getEnclosingClass()的
  105. if (includeEnclosing) {
  106. try {
  107. Class<?> enclosingClass = source.getEnclosingClass();
  108. if (enclosingClass != null) {
  109. R enclosingResult = processClassHierarchy(context, aggregateIndex,
  110. enclosingClass, processor, includeInterfaces, true);
  111. if (enclosingResult != null) {
  112. return enclosingResult;
  113. }
  114. }
  115. }
  116. catch (Throwable ex) {
  117. // ... 代码省略
  118. }
  119. }
  120. }
  121. catch (Throwable ex) {
  122. // ... 代码省略
  123. }
  124. return null;
  125. }
  126. }

4.2. 按方法处理

  1. abstract class AnnotationsScanner {
  2. private static <C, R> R processMethod(C context, Method source,
  3. SearchStrategy searchStrategy, AnnotationsProcessor<C, R> processor) {
  4. switch (searchStrategy) {
  5. // 只搜索自身的注解
  6. case DIRECT:
  7. // 搜索自身与标记为@Inherited父类的注解
  8. case INHERITED_ANNOTATIONS:
  9. return processMethodInheritedAnnotations(context, source, processor);
  10. // 搜索自身与父类的注解
  11. case SUPERCLASS:
  12. return processMethodHierarchy(context, new int[] {0}, source.getDeclaringClass(),
  13. processor, source, false);
  14. // 搜索自身、父类、接口的注解
  15. case TYPE_HIERARCHY:
  16. // 搜索自身、父类、接口、getEnclosingClass()的注解
  17. case TYPE_HIERARCHY_AND_ENCLOSING_CLASSES:
  18. return processMethodHierarchy(context, new int[] {0}, source.getDeclaringClass(),
  19. processor, source, true);
  20. }
  21. throw new IllegalStateException("Unsupported search strategy " + searchStrategy);
  22. }
  23. // 搜索自身与标记为@Inherited父类的注解
  24. private static <C, R> R processMethodInheritedAnnotations(C context, Method source,
  25. AnnotationsProcessor<C, R> processor) {
  26. try {
  27. // 聚合处理,如果有了,直接返回(默认未实现)
  28. // 不然,用processMethodAnnotations处理
  29. R result = processor.doWithAggregate(context, 0);
  30. return (result != null ? result :
  31. processMethodAnnotations(context, 0, source, processor));
  32. }
  33. catch (Throwable ex) {
  34. // ... 代码省略
  35. }
  36. return null;
  37. }
  38. // 处理方法的注解
  39. private static <C, R> R processMethodAnnotations(C context, int aggregateIndex, Method source,
  40. AnnotationsProcessor<C, R> processor) {
  41. // 获取所有public的注解
  42. Annotation[] annotations = getDeclaredAnnotations(source, false);
  43. // 处理器自定义处理
  44. R result = processor.doWithAnnotations(context, aggregateIndex, source, annotations);
  45. // 如果有了,返回
  46. if (result != null) {
  47. return result;
  48. }
  49. // ... 代码省略,桥接方法的处理
  50. return null;
  51. }
  52. // 搜索自身、父类、接口、getEnclosingClass()的注解
  53. private static <C, R> R processMethodHierarchy(C context, int[] aggregateIndex,
  54. Class<?> sourceClass, AnnotationsProcessor<C, R> processor, Method rootMethod,
  55. boolean includeInterfaces) {
  56. try {
  57. // 聚合处理,如果有了,直接返回(默认未实现)
  58. R result = processor.doWithAggregate(context, aggregateIndex[0]);
  59. if (result != null) {
  60. return result;
  61. }
  62. // 如果是Ordered或"java."开头,返回
  63. if (hasPlainJavaAnnotationsOnly(sourceClass)) {
  64. return null;
  65. }
  66. boolean calledProcessor = false;
  67. // 如果rootMethod是sourceClass的,直接处理
  68. if (sourceClass == rootMethod.getDeclaringClass()) {
  69. result = processMethodAnnotations(context, aggregateIndex[0],
  70. rootMethod, processor);
  71. calledProcessor = true;
  72. if (result != null) {
  73. return result;
  74. }
  75. }
  76. else {
  77. // 获取sourceClass的public方法
  78. for (Method candidateMethod : getBaseTypeMethods(context, sourceClass)) {
  79. // 如果方法不是private,并且参数与rootMethod一直,直接处理
  80. if (candidateMethod != null && isOverride(rootMethod, candidateMethod)) {
  81. result = processMethodAnnotations(context, aggregateIndex[0],
  82. candidateMethod, processor);
  83. calledProcessor = true;
  84. if (result != null) {
  85. return result;
  86. }
  87. }
  88. }
  89. }
  90. // 如果rootMethod是private,返回null
  91. if (Modifier.isPrivate(rootMethod.getModifiers())) {
  92. return null;
  93. }
  94. // 如果包括接口,继续搜索接口的
  95. if (includeInterfaces) {
  96. for (Class<?> interfaceType : sourceClass.getInterfaces()) {
  97. R interfacesResult = processMethodHierarchy(context, aggregateIndex,
  98. interfaceType, processor, rootMethod, true);
  99. if (interfacesResult != null) {
  100. return interfacesResult;
  101. }
  102. }
  103. }
  104. // 如果有父类,继续搜索父类的
  105. Class<?> superclass = sourceClass.getSuperclass();
  106. if (superclass != Object.class && superclass != null) {
  107. R superclassResult = processMethodHierarchy(context, aggregateIndex,
  108. superclass, processor, rootMethod, includeInterfaces);
  109. if (superclassResult != null) {
  110. return superclassResult;
  111. }
  112. }
  113. }
  114. catch (Throwable ex) {
  115. // ... 代码省略
  116. }
  117. return null;
  118. }
  119. }

4.3 按普通处理

  1. abstract class AnnotationsScanner {
  2. private static <C, R> R processElement(C context, AnnotatedElement source,
  3. AnnotationsProcessor<C, R> processor) {
  4. try {
  5. // 聚合处理,如果有了,直接返回(默认未实现)
  6. // 不然,调用getDeclaredAnnotations获取注解来处理
  7. R result = processor.doWithAggregate(context, 0);
  8. return (result != null ? result : processor.doWithAnnotations(
  9. context, 0, source, getDeclaredAnnotations(source, false)));
  10. }
  11. catch (Throwable ex) {
  12. // ... 代码省略
  13. }
  14. return null;
  15. }
  16. }

后续

更多博客,查看 https://github.com/senntyou/blogs

作者:深予之 (@senntyou)

版权声明:自由转载-非商用-非衍生-保持署名(创意共享 3.0 许可证

相关文章