Spring 源码解析九:默认的注解处理器

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

在 Spring 源码解析五:Bean 的配置、定义、注册 中,有一些默认的注解处理器还未解析

1. ConfigurationClassPostProcessor

ConfigurationClassPostProcessor
的主要功能是处理@Configuration

  1. public class ConfigurationClassPostProcessor implements BeanDefinitionRegistryPostProcessor,
  2. PriorityOrdered, ResourceLoaderAware, ApplicationStartupAware, BeanClassLoaderAware, EnvironmentAware {
  3. // 后置处理registry
  4. @Override
  5. public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
  6. // ... 代码省略
  7. // 处理配置类bean定义
  8. processConfigBeanDefinitions(registry);
  9. }
  10. // 后置处理registry
  11. @Override
  12. public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
  13. // ... 代码省略
  14. // 处理配置类bean定义
  15. processConfigBeanDefinitions((BeanDefinitionRegistry) beanFactory);
  16. // 使用ConfigurationClassEnhancer对@Configuration的class进行cglib增强
  17. enhanceConfigurationClasses(beanFactory);
  18. // ... 代码省略
  19. }
  20. }
  1. public class ConfigurationClassPostProcessor implements BeanDefinitionRegistryPostProcessor,
  2. PriorityOrdered, ResourceLoaderAware, ApplicationStartupAware, BeanClassLoaderAware, EnvironmentAware {
  3. // 处理配置类bean定义
  4. public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {
  5. // 配置类集合
  6. List<BeanDefinitionHolder> configCandidates = new ArrayList<>();
  7. // 所有bean的名字
  8. String[] candidateNames = registry.getBeanDefinitionNames();
  9. // 遍历
  10. for (String beanName : candidateNames) {
  11. // 获取bean定义
  12. BeanDefinition beanDef = registry.getBeanDefinition(beanName);
  13. // ... 代码省略
  14. // 如果是@Configuration标记的类,加入集合
  15. if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)) {
  16. configCandidates.add(new BeanDefinitionHolder(beanDef, beanName));
  17. }
  18. }
  19. // 没有@Configuration标记的类,返回
  20. if (configCandidates.isEmpty()) {
  21. return;
  22. }
  23. // ... 代码省略
  24. // 获取 @Configuration 类解析器
  25. ConfigurationClassParser parser = new ConfigurationClassParser(
  26. this.metadataReaderFactory, this.problemReporter, this.environment,
  27. this.resourceLoader, this.componentScanBeanNameGenerator, registry);
  28. // 待解析集合
  29. Set<BeanDefinitionHolder> candidates = new LinkedHashSet<>(configCandidates);
  30. // 已解析集合
  31. Set<ConfigurationClass> alreadyParsed = new HashSet<>(configCandidates.size());
  32. do {
  33. // ... 代码省略
  34. // 解析配置类
  35. parser.parse(candidates);
  36. // 验证配置类
  37. parser.validate();
  38. // 获取所有的配置类,包括以前注册的
  39. Set<ConfigurationClass> configClasses = new LinkedHashSet<>(parser.getConfigurationClasses());
  40. // 移除已解析的
  41. configClasses.removeAll(alreadyParsed);
  42. if (this.reader == null) {
  43. // 使用ConfigurationClassBeanDefinitionReader创建配置类bean定义读取器
  44. this.reader = new ConfigurationClassBeanDefinitionReader(
  45. registry, this.sourceExtractor, this.resourceLoader, this.environment,
  46. this.importBeanNameGenerator, parser.getImportRegistry());
  47. }
  48. // 读取bean定义
  49. this.reader.loadBeanDefinitions(configClasses);
  50. // 添加到已解析
  51. alreadyParsed.addAll(configClasses);
  52. // ... 代码省略
  53. }
  54. while (!candidates.isEmpty());
  55. // ... 代码省略
  56. }
  57. }

@Configuration类的处理核心是 ConfigurationClassParser
实现的

  1. class ConfigurationClassParser {
  2. public void parse(Set<BeanDefinitionHolder> configCandidates) {
  3. for (BeanDefinitionHolder holder : configCandidates) {
  4. BeanDefinition bd = holder.getBeanDefinition();
  5. try {
  6. // AnnotatedBeanDefinition处理
  7. if (bd instanceof AnnotatedBeanDefinition) {
  8. parse1(((AnnotatedBeanDefinition) bd).getMetadata(), holder.getBeanName());
  9. }
  10. // AbstractBeanDefinition+beanClass处理
  11. else if (bd instanceof AbstractBeanDefinition && ((AbstractBeanDefinition) bd).hasBeanClass()) {
  12. parse2(((AbstractBeanDefinition) bd).getBeanClass(), holder.getBeanName());
  13. }
  14. // 默认处理
  15. else {
  16. parse3(bd.getBeanClassName(), holder.getBeanName());
  17. }
  18. }
  19. catch (BeanDefinitionStoreException ex) {
  20. // ... 代码省略
  21. }
  22. // ... 代码省略
  23. }
  24. // ... 代码省略
  25. }
  26. protected final void parse1(AnnotationMetadata metadata, String beanName) throws IOException {
  27. processConfigurationClass(new ConfigurationClass(metadata, beanName), DEFAULT_EXCLUSION_FILTER);
  28. }
  29. protected final void parse2(Class<?> clazz, String beanName) throws IOException {
  30. processConfigurationClass(new ConfigurationClass(clazz, beanName), DEFAULT_EXCLUSION_FILTER);
  31. }
  32. protected final void parse3(@Nullable String className, String beanName) throws IOException {
  33. MetadataReader reader = this.metadataReaderFactory.getMetadataReader(className);
  34. processConfigurationClass(new ConfigurationClass(reader, beanName), DEFAULT_EXCLUSION_FILTER);
  35. }
  36. }
  1. class ConfigurationClassParser {
  2. protected void processConfigurationClass(ConfigurationClass configClass, Predicate<String> filter) throws IOException {
  3. // ... 代码省略
  4. // 包裹成SourceClass
  5. SourceClass sourceClass = asSourceClass(configClass, filter);
  6. // 遍历处理配置类,及其父类
  7. do {
  8. sourceClass = doProcessConfigurationClass(configClass, sourceClass, filter);
  9. }
  10. while (sourceClass != null);
  11. // ... 代码省略
  12. }
  13. // 处理配置类
  14. protected final SourceClass doProcessConfigurationClass(
  15. ConfigurationClass configClass, SourceClass sourceClass, Predicate<String> filter)
  16. throws IOException {
  17. // 处理@Component注解
  18. if (configClass.getMetadata().isAnnotated(Component.class.getName())) {
  19. // 遍历处理内部类(非静态内部类)
  20. processMemberClasses(configClass, sourceClass, filter);
  21. }
  22. // 处理@PropertySource注解,装载属性都bean中
  23. for (AnnotationAttributes propertySource : AnnotationConfigUtils.attributesForRepeatable(
  24. sourceClass.getMetadata(), PropertySources.class,
  25. org.springframework.context.annotation.PropertySource.class)) {
  26. // 装载属性都bean中
  27. processPropertySource(propertySource);
  28. }
  29. // 处理@ComponentScan注解,扫描指定的包
  30. Set<AnnotationAttributes> componentScans = AnnotationConfigUtils.attributesForRepeatable(
  31. sourceClass.getMetadata(), ComponentScans.class, ComponentScan.class);
  32. if (!componentScans.isEmpty() &&
  33. !this.conditionEvaluator.shouldSkip(sourceClass.getMetadata(), ConfigurationPhase.REGISTER_BEAN)) {
  34. // 遍历扫描
  35. for (AnnotationAttributes componentScan : componentScans) {
  36. // 扫描到的bean定义
  37. Set<BeanDefinitionHolder> scannedBeanDefinitions =
  38. this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName());
  39. // 遍历bean定义
  40. for (BeanDefinitionHolder holder : scannedBeanDefinitions) {
  41. BeanDefinition bdCand = holder.getBeanDefinition().getOriginatingBeanDefinition();
  42. // 如果也标记有@Configuration,继续解析
  43. if (ConfigurationClassUtils.checkConfigurationClassCandidate(bdCand, this.metadataReaderFactory)) {
  44. parse(bdCand.getBeanClassName(), holder.getBeanName());
  45. }
  46. }
  47. }
  48. }
  49. // 处理@Import注解
  50. processImports(configClass, sourceClass, getImports(sourceClass), filter, true);
  51. // 处理@ImportResource注解
  52. AnnotationAttributes importResource =
  53. AnnotationConfigUtils.attributesFor(sourceClass.getMetadata(), ImportResource.class);
  54. if (importResource != null) {
  55. // ... 代码省略
  56. }
  57. // 处理类中标记为@Bean的方法
  58. Set<MethodMetadata> beanMethods = retrieveBeanMethodMetadata(sourceClass);
  59. for (MethodMetadata methodMetadata : beanMethods) {
  60. configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass));
  61. }
  62. // 如果类是接口,注入默认的方法
  63. processInterfaces(configClass, sourceClass);
  64. // 如果有父类,返回父类,继续遍历
  65. if (sourceClass.getMetadata().hasSuperClass()) {
  66. // ... 代码省略
  67. }
  68. // 没有父类,结束遍历
  69. return null;
  70. }
  71. }

2. AutowiredAnnotationBeanPostProcessor

ConfigurationClassPostProcessor
的主要功能是处理 bean 的自动装配

  1. public class AutowiredAnnotationBeanPostProcessor implements SmartInstantiationAwareBeanPostProcessor,
  2. MergedBeanDefinitionPostProcessor, PriorityOrdered, BeanFactoryAware {
  3. // 默认处理@Autowired、@Value、@Inject三个注解
  4. public AutowiredAnnotationBeanPostProcessor() {
  5. this.autowiredAnnotationTypes.add(Autowired.class);
  6. this.autowiredAnnotationTypes.add(Value.class);
  7. try {
  8. this.autowiredAnnotationTypes.add((Class<? extends Annotation>)
  9. ClassUtils.forName("javax.inject.Inject", AutowiredAnnotationBeanPostProcessor.class.getClassLoader()));
  10. }
  11. catch (ClassNotFoundException ex) {
  12. // ... 代码省略
  13. }
  14. }
  15. // 处理属性注入
  16. @Override
  17. public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
  18. // 查找需要注入的元信息
  19. InjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass(), pvs);
  20. try {
  21. // 注入
  22. metadata.inject(bean, beanName, pvs);
  23. }
  24. catch (BeanCreationException ex) {
  25. // ... 代码省略
  26. }
  27. return pvs;
  28. }
  29. // 查找需要注入的元信息
  30. private InjectionMetadata findAutowiringMetadata(String beanName, Class<?> clazz, @Nullable PropertyValues pvs) {
  31. // 加锁的方式取出
  32. InjectionMetadata metadata = this.injectionMetadataCache.get(cacheKey);
  33. if (InjectionMetadata.needsRefresh(metadata, clazz)) {
  34. synchronized (this.injectionMetadataCache) {
  35. metadata = this.injectionMetadataCache.get(cacheKey);
  36. if (InjectionMetadata.needsRefresh(metadata, clazz)) {
  37. if (metadata != null) {
  38. metadata.clear(pvs);
  39. }
  40. // 构建元信息
  41. metadata = buildAutowiringMetadata(clazz);
  42. this.injectionMetadataCache.put(cacheKey, metadata);
  43. }
  44. }
  45. }
  46. return metadata;
  47. }
  48. }
  1. public class AutowiredAnnotationBeanPostProcessor implements SmartInstantiationAwareBeanPostProcessor,
  2. MergedBeanDefinitionPostProcessor, PriorityOrdered, BeanFactoryAware {
  3. // 构建元信息
  4. private InjectionMetadata buildAutowiringMetadata(final Class<?> clazz) {
  5. // ... 代码省略
  6. // 注入元素集合
  7. List<InjectionMetadata.InjectedElement> elements = new ArrayList<>();
  8. Class<?> targetClass = clazz;
  9. do {
  10. // 当前元素集合
  11. final List<InjectionMetadata.InjectedElement> currElements = new ArrayList<>();
  12. // 遍历本地属性
  13. ReflectionUtils.doWithLocalFields(targetClass, field -> {
  14. // 获取@Autowired、@Value、@Inject注解
  15. MergedAnnotation<?> ann = findAutowiredAnnotation(field);
  16. if (ann != null) {
  17. if (Modifier.isStatic(field.getModifiers())) {
  18. // 静态属性不能注入
  19. return;
  20. }
  21. // required 配置
  22. boolean required = determineRequiredStatus(ann);
  23. // 加入属性元素
  24. currElements.add(new AutowiredFieldElement(field, required));
  25. }
  26. });
  27. // 遍历本地方法
  28. ReflectionUtils.doWithLocalMethods(targetClass, method -> {
  29. Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
  30. // ... 代码省略
  31. // 获取@Autowired、@Value、@Inject注解
  32. MergedAnnotation<?> ann = findAutowiredAnnotation(bridgedMethod);
  33. if (ann != null) {
  34. if (Modifier.isStatic(method.getModifiers())) {
  35. // 静态方法不能注入
  36. return;
  37. }
  38. // required 配置
  39. boolean required = determineRequiredStatus(ann);
  40. PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
  41. // 加入方法元素
  42. currElements.add(new AutowiredMethodElement(method, required, pd));
  43. }
  44. });
  45. // 添加进注入元素集合
  46. elements.addAll(0, currElements);
  47. // 遍历父类
  48. targetClass = targetClass.getSuperclass();
  49. }
  50. while (targetClass != null && targetClass != Object.class);
  51. return InjectionMetadata.forElements(elements, clazz);
  52. }
  53. }

属性的注入是 AutowiredFieldElement.inject 完成的,方法参数的注入是 AutowiredMethodElement.inject 完成的

  1. private class AutowiredFieldElement extends InjectionMetadata.InjectedElement {
  2. @Override
  3. protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
  4. Field field = (Field) this.member;
  5. Object value;
  6. if (this.cached) {
  7. // 先从缓存中获取bean,其次从registry获取bean
  8. value = resolvedCachedArgument(beanName, this.cachedFieldValue);
  9. }
  10. else {
  11. // 实例化一个DependencyDescriptor对象
  12. DependencyDescriptor desc = new DependencyDescriptor(field, this.required);
  13. // ... 代码省略
  14. try {
  15. // 从registry获取bean
  16. value = beanFactory.resolveDependency(desc, beanName, autowiredBeanNames, typeConverter);
  17. }
  18. catch (BeansException ex) {
  19. // ... 代码省略
  20. }
  21. synchronized (this) {
  22. // ... 代码省略
  23. // 把autowiredBeanNames注册为beanName的依赖
  24. registerDependentBeans(beanName, autowiredBeanNames);
  25. // ... 代码省略
  26. }
  27. }
  28. // 把bean注入到属性中
  29. if (value != null) {
  30. ReflectionUtils.makeAccessible(field);
  31. field.set(bean, value);
  32. }
  33. }
  34. }
  1. private class AutowiredMethodElement extends InjectionMetadata.InjectedElement {
  2. @Override
  3. protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
  4. // ... 代码省略
  5. Method method = (Method) this.member;
  6. Object[] arguments;
  7. if (this.cached) {
  8. // 先从缓存中获取参数bean集合,其次从registry获取参数bean集合
  9. arguments = resolveCachedArguments(beanName);
  10. }
  11. else {
  12. // 参数个数
  13. int argumentCount = method.getParameterCount();
  14. // 参数集合
  15. arguments = new Object[argumentCount];
  16. // ... 代码省略
  17. for (int i = 0; i < arguments.length; i++) {
  18. // 参数对象
  19. MethodParameter methodParam = new MethodParameter(method, i);
  20. // ... 代码省略
  21. try {
  22. // 获取参数注入的bean
  23. Object arg = beanFactory.resolveDependency(currDesc, beanName, autowiredBeans, typeConverter);
  24. // ... 代码省略
  25. arguments[i] = arg;
  26. }
  27. catch (BeansException ex) {
  28. // ... 代码省略
  29. }
  30. }
  31. // ... 代码省略
  32. }
  33. // 把bean注入到参数中
  34. if (arguments != null) {
  35. try {
  36. ReflectionUtils.makeAccessible(method);
  37. method.invoke(bean, arguments);
  38. }
  39. catch (InvocationTargetException ex) {
  40. // ... 代码省略
  41. }
  42. }
  43. }
  44. }

3. CommonAnnotationBeanPostProcessor

CommonAnnotationBeanPostProcessor
的主要功能是处理通用 java 注解javax.annotation.*

  1. public class CommonAnnotationBeanPostProcessor extends InitDestroyAnnotationBeanPostProcessor
  2. implements InstantiationAwareBeanPostProcessor, BeanFactoryAware, Serializable {
  3. // 处理属性注入
  4. @Override
  5. public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
  6. // 查找需要注入的元信息
  7. InjectionMetadata metadata = findResourceMetadata(beanName, bean.getClass(), pvs);
  8. try {
  9. // 注入
  10. metadata.inject(bean, beanName, pvs);
  11. }
  12. catch (Throwable ex) {
  13. // ... 代码省略
  14. }
  15. return pvs;
  16. }
  17. // 查找需要注入的元信息
  18. private InjectionMetadata findResourceMetadata(String beanName, final Class<?> clazz, @Nullable PropertyValues pvs) {
  19. // 加锁的方式取出
  20. InjectionMetadata metadata = this.injectionMetadataCache.get(cacheKey);
  21. if (InjectionMetadata.needsRefresh(metadata, clazz)) {
  22. synchronized (this.injectionMetadataCache) {
  23. metadata = this.injectionMetadataCache.get(cacheKey);
  24. if (InjectionMetadata.needsRefresh(metadata, clazz)) {
  25. if (metadata != null) {
  26. metadata.clear(pvs);
  27. }
  28. // 构建元信息
  29. metadata = buildResourceMetadata(clazz);
  30. this.injectionMetadataCache.put(cacheKey, metadata);
  31. }
  32. }
  33. }
  34. return metadata;
  35. }
  36. }
  1. public class CommonAnnotationBeanPostProcessor extends InitDestroyAnnotationBeanPostProcessor
  2. implements InstantiationAwareBeanPostProcessor, BeanFactoryAware, Serializable {
  3. // 构建元信息
  4. private InjectionMetadata buildResourceMetadata(final Class<?> clazz) {
  5. // ... 代码省略
  6. // 注入元素集合
  7. List<InjectionMetadata.InjectedElement> elements = new ArrayList<>();
  8. Class<?> targetClass = clazz;
  9. do {
  10. // 当前元素集合
  11. final List<InjectionMetadata.InjectedElement> currElements = new ArrayList<>();
  12. // 遍历本地属性
  13. ReflectionUtils.doWithLocalFields(targetClass, field -> {
  14. // @WebServiceRef 注解
  15. if (webServiceRefClass != null && field.isAnnotationPresent(webServiceRefClass)) {
  16. if (Modifier.isStatic(field.getModifiers())) {
  17. // 静态属性不能注入
  18. }
  19. currElements.add(new WebServiceRefElement(field, field, null));
  20. }
  21. // @EJB 注解
  22. else if (ejbClass != null && field.isAnnotationPresent(ejbClass)) {
  23. if (Modifier.isStatic(field.getModifiers())) {
  24. // 静态属性不能注入
  25. }
  26. currElements.add(new EjbRefElement(field, field, null));
  27. }
  28. // @Resource 注解
  29. else if (field.isAnnotationPresent(Resource.class)) {
  30. if (Modifier.isStatic(field.getModifiers())) {
  31. // 静态属性不能注入
  32. }
  33. if (!this.ignoredResourceTypes.contains(field.getType().getName())) {
  34. currElements.add(new ResourceElement(field, field, null));
  35. }
  36. }
  37. });
  38. // 遍历本地方法
  39. ReflectionUtils.doWithLocalMethods(targetClass, method -> {
  40. Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
  41. // ... 代码省略
  42. // @WebServiceRef 注解
  43. if (webServiceRefClass != null && bridgedMethod.isAnnotationPresent(webServiceRefClass)) {
  44. if (Modifier.isStatic(method.getModifiers())) {
  45. // 静态方法不能注入
  46. }
  47. PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
  48. currElements.add(new WebServiceRefElement(method, bridgedMethod, pd));
  49. }
  50. // @EJB 注解
  51. else if (ejbClass != null && bridgedMethod.isAnnotationPresent(ejbClass)) {
  52. if (Modifier.isStatic(method.getModifiers())) {
  53. // 静态方法不能注入
  54. }
  55. PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
  56. currElements.add(new EjbRefElement(method, bridgedMethod, pd));
  57. }
  58. // @Resource 注解
  59. else if (bridgedMethod.isAnnotationPresent(Resource.class)) {
  60. if (Modifier.isStatic(method.getModifiers())) {
  61. // 静态方法不能注入
  62. }
  63. if (!this.ignoredResourceTypes.contains(paramTypes[0].getName())) {
  64. PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
  65. currElements.add(new ResourceElement(method, bridgedMethod, pd));
  66. }
  67. }
  68. });
  69. // 添加进注入元素集合
  70. elements.addAll(0, currElements);
  71. // 遍历父类
  72. targetClass = targetClass.getSuperclass();
  73. }
  74. while (targetClass != null && targetClass != Object.class);
  75. return InjectionMetadata.forElements(elements, clazz);
  76. }
  77. }

4. PersistenceAnnotationBeanPostProcessor

PersistenceAnnotationBeanPostProcessor
的主要功能是处理持久化 java 注解javax.persistence.*

  1. public class PersistenceAnnotationBeanPostProcessor
  2. implements InstantiationAwareBeanPostProcessor, DestructionAwareBeanPostProcessor,
  3. MergedBeanDefinitionPostProcessor, PriorityOrdered, BeanFactoryAware, Serializable {
  4. // 处理属性注入
  5. @Override
  6. public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
  7. // 查找需要注入的元信息
  8. InjectionMetadata metadata = findPersistenceMetadata(beanName, bean.getClass(), pvs);
  9. try {
  10. // 注入
  11. metadata.inject(bean, beanName, pvs);
  12. }
  13. catch (Throwable ex) {
  14. // ... 代码省略
  15. }
  16. return pvs;
  17. }
  18. // 查找需要注入的元信息
  19. private InjectionMetadata findPersistenceMetadata(String beanName, final Class<?> clazz, @Nullable PropertyValues pvs) {
  20. // 加锁的方式取出
  21. InjectionMetadata metadata = this.injectionMetadataCache.get(cacheKey);
  22. if (InjectionMetadata.needsRefresh(metadata, clazz)) {
  23. synchronized (this.injectionMetadataCache) {
  24. metadata = this.injectionMetadataCache.get(cacheKey);
  25. if (InjectionMetadata.needsRefresh(metadata, clazz)) {
  26. if (metadata != null) {
  27. metadata.clear(pvs);
  28. }
  29. // 构建元信息
  30. this.injectionMetadataCache.put(cacheKey, metadata);
  31. }
  32. }
  33. }
  34. return metadata;
  35. }
  36. }
  1. public class PersistenceAnnotationBeanPostProcessor
  2. implements InstantiationAwareBeanPostProcessor, DestructionAwareBeanPostProcessor,
  3. MergedBeanDefinitionPostProcessor, PriorityOrdered, BeanFactoryAware, Serializable {
  4. // 构建元信息
  5. private InjectionMetadata buildPersistenceMetadata(final Class<?> clazz) {
  6. // ... 代码省略
  7. // 注入元素集合
  8. List<InjectionMetadata.InjectedElement> elements = new ArrayList<>();
  9. Class<?> targetClass = clazz;
  10. do {
  11. // 当前元素集合
  12. final List<InjectionMetadata.InjectedElement> currElements = new ArrayList<>();
  13. // 遍历本地属性
  14. ReflectionUtils.doWithLocalFields(targetClass, field -> {
  15. // 有 @PersistenceContext、@PersistenceUnit 注解
  16. if (field.isAnnotationPresent(PersistenceContext.class) ||
  17. field.isAnnotationPresent(PersistenceUnit.class)) {
  18. if (Modifier.isStatic(field.getModifiers())) {
  19. // 静态属性不能注入
  20. }
  21. currElements.add(new PersistenceElement(field, field, null));
  22. }
  23. });
  24. // 遍历本地方法
  25. ReflectionUtils.doWithLocalMethods(targetClass, method -> {
  26. Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
  27. // ... 代码省略
  28. // 有 @PersistenceContext、@PersistenceUnit 注解
  29. if ((bridgedMethod.isAnnotationPresent(PersistenceContext.class) ||
  30. bridgedMethod.isAnnotationPresent(PersistenceUnit.class)) &&
  31. method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) {
  32. if (Modifier.isStatic(method.getModifiers())) {
  33. // 静态方法不能注入
  34. }
  35. PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
  36. currElements.add(new PersistenceElement(method, bridgedMethod, pd));
  37. }
  38. });
  39. // 添加进注入元素集合
  40. elements.addAll(0, currElements);
  41. // 遍历父类
  42. targetClass = targetClass.getSuperclass();
  43. }
  44. while (targetClass != null && targetClass != Object.class);
  45. return InjectionMetadata.forElements(elements, clazz);
  46. }
  47. }

5. EventListenerMethodProcessor

EventListenerMethodProcessor
的主要功能是处理事件监听@EventListener

  1. public class EventListenerMethodProcessor
  2. implements SmartInitializingSingleton, ApplicationContextAware, BeanFactoryPostProcessor {
  3. // 单例bean初始化后
  4. @Override
  5. public void afterSingletonsInstantiated() {
  6. ConfigurableListableBeanFactory beanFactory = this.beanFactory;
  7. // 获取所有的bean
  8. String[] beanNames = beanFactory.getBeanNamesForType(Object.class);
  9. for (String beanName : beanNames) {
  10. Class<?> type = null;
  11. try {
  12. // 获取bean类型
  13. type = AutoProxyUtils.determineTargetClass(beanFactory, beanName);
  14. }
  15. catch (Throwable ex) {
  16. // ... 代码省略
  17. }
  18. if (type != null) {
  19. // ... 代码省略
  20. try {
  21. // 处理 bean
  22. processBean(beanName, type);
  23. }
  24. catch (Throwable ex) {
  25. // ... 代码省略
  26. }
  27. }
  28. }
  29. }
  30. // 处理 bean
  31. private void processBean(final String beanName, final Class<?> targetType) {
  32. // 是以 org.springframework. 开头的类或有 @EventListener 注解
  33. if (!this.nonAnnotatedClasses.contains(targetType) &&
  34. AnnotationUtils.isCandidateClass(targetType, EventListener.class) &&
  35. !isSpringContainerClass(targetType)) {
  36. Map<Method, EventListener> annotatedMethods = null;
  37. try {
  38. // 选择有 @EventListener 注解的方法
  39. annotatedMethods = MethodIntrospector.selectMethods(targetType,
  40. (MethodIntrospector.MetadataLookup<EventListener>) method ->
  41. AnnotatedElementUtils.findMergedAnnotation(method, EventListener.class));
  42. }
  43. catch (Throwable ex) {
  44. // ... 代码省略
  45. }
  46. // 上下文对象
  47. ConfigurableApplicationContext context = this.applicationContext;
  48. // 监听器工厂
  49. List<EventListenerFactory> factories = this.eventListenerFactories;
  50. // 遍历方法
  51. for (Method method : annotatedMethods.keySet()) {
  52. // 遍历工厂
  53. for (EventListenerFactory factory : factories) {
  54. // 如果工厂直接解析监听方法
  55. if (factory.supportsMethod(method)) {
  56. // 包装方法
  57. Method methodToUse = AopUtils.selectInvocableMethod(method, context.getType(beanName));
  58. // 封装为标准的监听器
  59. ApplicationListener<?> applicationListener =
  60. factory.createApplicationListener(beanName, targetType, methodToUse);
  61. // ... 代码省略
  62. // 添加进上下文
  63. context.addApplicationListener(applicationListener);
  64. break;
  65. }
  66. }
  67. }
  68. }
  69. }
  70. }

6. DefaultEventListenerFactory

DefaultEventListenerFactory
的主要功能是封装有@EventListener注解的方法为标准的监听器

  1. public class DefaultEventListenerFactory implements EventListenerFactory, Ordered {
  2. @Override
  3. public ApplicationListener<?> createApplicationListener(String beanName, Class<?> type, Method method) {
  4. return new ApplicationListenerMethodAdapter(beanName, type, method);
  5. }
  6. }

本质上就是用 ApplicationListenerMethodAdapter

  1. public class ApplicationListenerMethodAdapter implements GenericApplicationListener {
  2. // 调用监听方法
  3. @Override
  4. public void onApplicationEvent(ApplicationEvent event) {
  5. processEvent(event);
  6. }
  7. // 处理事件
  8. public void processEvent(ApplicationEvent event) {
  9. // 获取调用方法的参数,如果有payload,获取payload,没有就是event本身
  10. Object[] args = resolveArguments(event);
  11. // 如果符合@EventListener的condition设置,则触发
  12. if (shouldHandle(event, args)) {
  13. // 调用method.invoke获取结果
  14. Object result = doInvoke(args);
  15. if (result != null) {
  16. // 以此结果,继续派发其他事件
  17. handleResult(result);
  18. }
  19. }
  20. }
  21. }

后续

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

作者:深予之 (@senntyou)

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

相关文章