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容器中拿到的值