Spring源码分析之Bean的创建过程详解 (5)

autowireByName 和 autowireByType差不多,autowireByType更为复杂一些,这里只分析autowireByType的处理过程

protected void autowireByType( String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) { // 查询非简单(Java内置 基本类型,String,Date等)的属性 String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw); // 循环所有属性名 for (String propertyName : propertyNames) { // 获取方法参数 MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd); // 构建一个依赖描述符 DependencyDescriptor desc = new AutowireByTypeDependencyDescriptor(methodParam, eager); // 获取依赖的bean // resolveDependency方法中调用了doResolveDependency,该方法我们在下一步的后置处理器调用中分析 Object autowiredArgument = resolveDependency(desc, beanName, autowiredBeanNames, converter); // 将bean放置到属性集合中 if (autowiredArgument != null) { pvs.add(propertyName, autowiredArgument); } } }

现在,回到填充属性的过程

该第六次调用后置处理器了,这一次主要对属性和方法进行自动装配

// CommonAnnotationBeanPostProcessor 处理@Resouce注解的装配 // AutowiredAnnotationBeanPostProcessor 处理@Autowired @Value @Inject注解的装配 for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof InstantiationAwareBeanPostProcessor) { InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp; // 处理自动装配,将依赖的属性装配到bean中 PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName); // ...省略已被废弃的代码... pvs = pvsToUse; } }

这一步的逻辑也是差不多,由于AutowiredAnnotationBeanPostProcessor复杂一些,我们取AutowiredAnnotationBeanPostProcessor中的逻辑进行分析

public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) { // 取出之前postProcessMergedBeanDefinition时解析好的元数据 // @Autowired @Value @Inject 标识的属性或方法 // findAutowiringMetadata这里有没有和第四步中的很像呢~ InjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass(), pvs); // 进行自动装配 metadata.inject(bean, beanName, pvs); return pvs; }

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); if (InjectionMetadata.needsRefresh(metadata, clazz)) { synchronized (this.injectionMetadataCache) { metadata = this.injectionMetadataCache.get(cacheKey); if (InjectionMetadata.needsRefresh(metadata, clazz)) { if (metadata != null) { metadata.clear(pvs); } // 构建元数据,找到@Autowird @Value @Inject 标识的属性或方法进行构建 metadata = buildAutowiringMetadata(clazz); this.injectionMetadataCache.put(cacheKey, metadata); } } } return metadata; }

自动装配过程

public void inject(Object target, @Nullable String beanName, @Nullable PropertyValues pvs) { // 取出之前去重过的元数据列表 Collection<InjectedElement> checkedElements = this.checkedElements; if (!elementsToIterate.isEmpty()) { for (InjectedElement element : elementsToIterate) { // 进行属性或方法装配 element.inject(target, beanName, pvs); } } } protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs){ // 强转成Field Field field = (Field) this.member; // 创建一个依赖描述符 DependencyDescriptor desc = new DependencyDescriptor(field, this.required); // 获取到依赖的bean value = beanFactory.resolveDependency(desc, beanName, autowiredBeanNames, typeConverter); if (value != null) { ReflectionUtils.makeAccessible(field); // 将获取到的依赖bean利用反射装配到属性中 field.set(bean, value); } } public Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName, @Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) { // 获取bean result = doResolveDependency(descriptor, requestingBeanName, autowiredBeanNames, typeConverter); return result; } public Object doResolveDependency(DependencyDescriptor descriptor, @Nullable String beanName, @Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter){ // 解析@Value注解 Object value = getAutowireCandidateResolver().getSuggestedValue(descriptor); if (value != null) { return converter.convertIfNecessary(value, type, descriptor.getTypeDescriptor()); } // 根据类型寻找是否有匹配的beanDefinition Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, descriptor); if (matchingBeans.isEmpty()) { // 为空则判断是否必须 if (isRequired(descriptor)) { // 必须则抛出NoSuchBeanDefinitionException异常 raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor); } return null; } // 如果根据类型匹配出来的候选bean不止一个,则需要确认是哪一个 if (matchingBeans.size() > 1) { // 确认出真正需要依赖的 // 先判断是否有@Primary注解的 // 没有再判断是否有实现了Priority注解的,取值最小的 // 没有最后使用属性名进行匹配 // 匹配不到则返回null autowiredBeanName = determineAutowireCandidate(matchingBeans, descriptor); if (autowiredBeanName == null) { // 这里进行确认是否必须,必须则抛出异常 if (isRequired(descriptor) || !indicatesMultipleBeans(type)) { return descriptor.resolveNotUnique(descriptor.getResolvableType(), matchingBeans); } else { return null; } } instanceCandidate = matchingBeans.get(autowiredBeanName); } if (instanceCandidate instanceof Class) { // 调用getBean方法 instanceCandidate = descriptor.resolveCandidate(autowiredBeanName, type, this); } Object result = instanceCandidate; return result; }

getBean方法

public Object resolveCandidate(String beanName, Class<?> requiredType, BeanFactory beanFactory) { return beanFactory.getBean(beanName); }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wpgxxy.html