spring源码解析 --AutowiredAnnotationBeanPostProcessor

本文深入探讨了Spring框架中依赖注入的实现机制,重点讲解了如何通过@Autowire注解来实现自动装配,并介绍了AutowiredAnnotationBeanPostProcessor的作用及其实现细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

bean实例化时会处理其属性值,其中有一步是对标注了@Autowire的字段进行解析,

较为复杂的是对于方法上标记了@Autowire


在对象实例化后,在doCreateBean中会调用

 

 

 AutowiredAnnotationBeanPostProcessor实现了MergedBeanDefinitionPostProcessor

 AutowiredAnnotationBeanPostProcessor#postProcessMergedBeanDefinition源码

 

 

private InjectionMetadata findAutowiringMetadata(String beanName, Class<?> clazz, @Nullable PropertyValues pvs) {
// Fall back to class name as cache key, for backwards compatibility with custom callers.


		String cacheKey = (StringUtils.hasLength(beanName) ? beanName : clazz.getName());
		// Quick check on the concurrent map first, with minimal locking.
		InjectionMetadata metadata = this.injectionMetadataCache.get(cacheKey);
		if (InjectionMetadata.needsRefresh(metadata, clazz)) {
			synchronized (this.injectionMetadataCache) {
				metadata = this.injectionMetadataCache.get(cacheKey);
				if (InjectionMetadata.needsRefresh(metadata, clazz)) {
					if (metadata != null) {
						metadata.clear(pvs);
					}
//如果缓存里没有找到该beanName为key对应的InjectionMetadata,就在通过class进行创建
					metadata = buildAutowiringMetadata(clazz);
					this.injectionMetadataCache.put(cacheKey, metadata);
				}
			}
		}
		return metadata;
	}

  其中metadata是标记了@Autowire的方法或属性的封装类的集合,不是普通属性字段会有标记

AutowiredAnnotationBeanPostProcessor#buildAutowiringMetadata方法大致作用是通过class将类中标记了如@Autowire的属性和方法都创建对应的InjectionMetadata.InjectionElement实例对象

最后保存在injectedElements Set集合中

且injectedElement实例对象的类型为AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement

 

InjectionMetadata#checkConfigMembers会进行检查,通过检查的会放入InjectionMetadata.checkedElements中

 这一切做完以后AutowiredAnnotationBeanPostProcessor.injectionMetadataCache已经保存有

beanName为keyInjectionMetadata为value的缓存了

接着进行属性的填充,开始正式处理这些value

 AutowiredAnnotationBeanPostProcessor.实现了InstantiationAwareBeanPostProcessor

会进行调用postProcessProperties

查看postProcessAfterInstantiation源码

public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
//获取元数据信息,如果缓存中有则从缓存中拿,没有就再生成
		InjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass(), pvs);
		try {
//开始处理
			metadata.inject(bean, beanName, pvs);
		}
		catch (BeanCreationException ex) {
			throw ex;
		}
		catch (Throwable ex) {
			throw new BeanCreationException(beanName, "Injection of autowired dependencies failed", ex);
		}
		return pvs;
	}

元数据对象会调用实例为AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement#inject

该方法会为最后method.invoke准备实参,实参如下是通过beanFactory同过各种信息拿到bean对象

 

举个例子

如下,它的参数就是通过这种形式在ioc容器中拿到的值

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值