在上一篇文章中,我们分析了Spring中Bean的实例化过程,在结尾我们知道了虽然bean的实例化完成了,但是其中的属性还没有被注入,今天我们就接着来分析属性是如何被注入的。
实例化完成后,回到上面第3条的doCreateBean
方法中,看一下用BeanWrapper
产生的原生对象,里面dao
这个属性还是null
值。
回归一下之前的代码,接下来要调用populateBean
方法进行属性的填充:
Object exposedObject = bean; try { populateBean(beanName, mbd, instanceWrapper); exposedObject = initializeBean(beanName, exposedObject, mbd); }
看一下populateBean
中的核心代码:
for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof InstantiationAwareBeanPostProcessor) { InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp; pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName); if (pvs == null) { return; } } }
这里通过getBeanPostProcessors
方法获得当前注册的所有后置处理器,如果属于InstantiationAwareBeanPostProcessor
类型,则调用它的postProcessPropertyValues
方法。通过遍历,可以知道当前spring中存在7个后置处理器:
我们主要来看一下AutowiredAnnotationBeanPostProcessor
,因为它负责对添加了 @Autowired
、@Value
等注解的属性进行依赖的填充。进入它的postProcessPropertyValues
方法:
public PropertyValues postProcessPropertyValues( PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeanCreationException { InjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass(), pvs); try { metadata.inject(bean, beanName, pvs); } //异常处理代码省略... return pvs; }
这里的InjectionMetadata
可以理解为要注入的属性的元数据,在它里面维护了一个Collection
,来存放所有需要注入的bean:
private final CollectioninjectedElements;
进入findAutowiringMetadata
方法:
private InjectionMetadata findAutowiringMetadata(String beanName, Class> clazz, @Nullable PropertyValues pvs) { String cacheKey = (StringUtils.hasLength(beanName) ? beanName : clazz.getName()); InjectionMetadata metadata = this.injectionMetadataCache.get(cacheKey); //省略非重要代码... return metadata; }
在执行完这一步后,就把需要填充的属性放进了刚才提到的injectedElements
中:
接下来,继续执行InjectionMetadata
的inject
方法,在其中遍历所有需要注入的属性的列表,遍历调用AutowiredAnnotationBeanPostProcessor的inject
方法:
protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable { Field field = (Field) this.member; Object value; if (this.cached) { value = resolvedCachedArgument(beanName, this.cachedFieldValue); } else { DependencyDescriptor desc = new DependencyDescriptor(field, this.required); desc.setContainingClass(bean.getClass()); SetautowiredBeanNames = new LinkedHashSet<>(1); Assert.state(beanFactory != null, "No BeanFactory available"); TypeConverter typeCOnverter= beanFactory.getTypeConverter(); try {//用beanFactory解决依赖 value = beanFactory.resolveDependency(desc, beanName, autowiredBeanNames, typeConverter); } //后面代码省略...
这里创建了一个DependencyDescriptor
,用来维护注入属性与它的容器类containingClass
的关系,里面最重要的就是存放了注入属性的类型、名称,以及containingClass
的类型等信息。
调用resolveDependency
方法,其中没有做什么实质性的工作,继续调用了doResolveDependency
方法:
public Object doResolveDependency(DependencyDescriptor descriptor, @Nullable String beanName, @Nullable SetautowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException { InjectionPoint previousInjectiOnPoint= ConstructorResolver.setCurrentInjectionPoint(descriptor); try { Object shortcut = descriptor.resolveShortcut(this); if (shortcut != null) { return shortcut; } //依赖的属性值的类型 Class> type = descriptor.getDependencyType(); Object value = getAutowireCandidateResolver().getSuggestedValue(descriptor); if (value != null) { if (value instanceof String) { String strVal = resolveEmbeddedValue((String) value); BeanDefinition bd = (beanName != null && containsBean(beanName) ? getMergedBeanDefinition(beanName) : null); value = evaluateBeanDefinitionString(strVal, bd); } TypeConverter cOnverter= (typeConverter != null ? typeConverter : getTypeConverter()); return (descriptor.getField() != null ? converter.convertIfNecessary(value, type, descriptor.getField()) : converter.convertIfNecessary(value, type, descriptor.getMethodParameter())); } Object multipleBeans = resolveMultipleBeans(descriptor, beanName, autowiredBeanNames, typeConverter); if (multipleBeans != null) { return multipleBeans; } //把匹配的值和类型拿出来,放到一个map中 Map matchingBeans = findAutowireCandidates(beanName, type, descriptor); if (matchingBeans.isEmpty()) { if (isRequired(descriptor)) { raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor); } return null; } String autowiredBeanName; Object instanceCandidate; //如果有超过一个匹配的,可能会有错误 if (matchingBeans.size() > 1) { autowiredBeanName = determineAutowireCandidate(matchingBeans, descriptor); if (autowiredBeanName == null) { if (isRequired(descriptor) || !indicatesMultipleBeans(type)) { return descriptor.resolveNotUnique(type, matchingBeans); } else { return null; } } instanceCandidate = matchingBeans.get(autowiredBeanName); } else { Map.Entry entry = matchingBeans.entrySet().iterator().next(); autowiredBeanName = entry.getKey(); instanceCandidate = entry.getValue(); } if (autowiredBeanNames != null) { //把找到的bean的名字放到set中 autowiredBeanNames.add(autowiredBeanName); } if (instanceCandidate instanceof Class) { // 实际获取注入的bean instanceCandidate = descriptor.resolveCandidate(autowiredBeanName, type, this); } Object result = instanceCandidate; if (result instanceof NullBean) { if (isRequired(descriptor)) { raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor); } result = null; } if (!ClassUtils.isAssignableValue(type, result)) { throw new BeanNotOfRequiredTypeException(autowiredBeanName, type, instanceCandidate.getClass()); } return result; } finally { ConstructorResolver.setCurrentInjectionPoint(previousInjectionPoint); } }
通过findAutowireCandidates
方法,获取与注入属性匹配的值和类型,放到一个Map当中,再通过它的beanName
,调用resolveCandidate
方法,实际获取注入的bean实例。这一操作底层调用的也是BeanFactory的getBean
方法。
回到inject
方法,使用反射将注入的bean实例赋值给属性:
ReflectionUtils.makeAccessible(field); field.set(bean, value);
在执行完populateBean
方法后,依赖的属性已经被注入成功了。
在bean实例化完成后,执行各种回调和后置管理器方法:
protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) { if (System.getSecurityManager() != null) { AccessController.doPrivileged((PrivilegedAction) () -> { invokeAwareMethods(beanName, bean); return null; }, getAccessControlContext()); } else { //若bean实现了BeanNameAware、BeanClassLoaderAware、BeanFactoryAware接口,执行回调方法 invokeAwareMethods(beanName, bean); } Object wrappedBean = bean; if (mbd == null || !mbd.isSynthetic()) { //执行所有后置处理器的before方法 wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName); } try { //执行bean生命周期回调中的init-method //若bean实现了InitializingBean接口,执行afterPropertiesSet方法 invokeInitMethods(beanName, wrappedBean, mbd); } catch (Throwable ex) { throw new BeanCreationException( (mbd != null ? mbd.getResourceDescription() : null), beanName, "Invocation of init method failed", ex); } if (mbd == null || !mbd.isSynthetic()) { //执行所有后置处理器的after方法 wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName); } return wrappedBean; }
具体执行内容:
BeanNameAware
、BeanClassLoaderAware
、BeanFactoryAware
接口,执行回调方法postProcessBeforeInitialization
方法init-method
,若bean实现了InitializingBean
接口,执行afterPropertiesSet
方法postProcessAfterInitialization
方法在这一步完成后,bean的实例化过程全部结束。最后执行一下refresh
方法中的finishRefresh
方法,进行广播事件等操作。到这,一个完整的AnnotationConfigApplicationContext
初始化就完成了。
到此这篇关于Spring源码解析 Bean属性填充的文章就介绍到这了,更多相关Spring Bean属性填充内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!