spring源码系列---依赖注入

org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#doCreateBean

protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
			throws BeanCreationException {

		// 实例化bean
		// Instantiate the bean.
		BeanWrapper instanceWrapper = null;
		if (mbd.isSingleton()) {
			instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
		}
		if (instanceWrapper == null) {
			// TODO 先创建Bean实例,推断构造方法入口(通过factoryBean工厂、有参数构造函数、无参数构造函数初始化)
			instanceWrapper = createBeanInstance(beanName, mbd, args);
		}
		Object bean = instanceWrapper.getWrappedInstance();
		Class<?> beanType = instanceWrapper.getWrappedClass();
		if (beanType != NullBean.class) {
			mbd.resolvedTargetType = beanType;
		}

		// 允许后置处理器修改合并的bean定义
		// 这里的mbd为合并后的BeanDefinition
		// Allow post-processors to modify the merged bean definition.
		synchronized (mbd.postProcessingLock) {
			if (!mbd.postProcessed) {
				try {
					// 执行合并后的BeanDefinition后置处理器
					// TODO 这里会查找@Autowired的注入点(InjectedElement)
					// CommonAnnotationBeanPostProcessor  支持@BeanPostConstruct、@PreDestory、@Resource
					// AutowiredAnnotationBeanPostProcessor  支持@Autowire注解和@Value注解
					// BeanPostProcessor接口的典型应用
					applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
				}
				catch (Throwable ex) {
					throw new BeanCreationException(mbd.getResourceDescription(), beanName,
							"Post-processing of merged bean definition failed", ex);
				}
				mbd.postProcessed = true;
			}
		}

		// 如果当前创建的是单例bean,并且运行循环依赖,并且还在创建中,那么则提早暴露
		// Eagerly cache singletons to be able to resolve circular references
		// even when triggered by lifecycle interfaces like BeanFactoryAware.
		boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
				isSingletonCurrentlyInCreation(beanName));
		if (earlySingletonExposure) {
			if (logger.isTraceEnabled()) {
				logger.trace("Eagerly caching bean '" + beanName +
						"' to allow for resolving potential circular references");
			}
			// 此时bean还没有完成属性注入,是一个简单的对象
			// 构造一个对象工厂添加到三级缓存singletonFactories中
			// 重点!!!将实例化的对象添加到singletonFactories中
			// 第四次调用后置处理器
			addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
		}

		// 对象已经暴露出去
		// 在创建单例bean的时候会存在依赖注入的情况,为了避免循环依赖Spring在创建bean的时候,是不能bean创建完成就会将创建bean的ObjectFactory提早曝光
		// Initialize the bean instance.
		Object exposedObject = bean;
		try {
			// 3、填充属性  @Autowired
			// ioc DI 的过程
			// 扫描注解信息,Autowired、Resource、PostConstruct、PreDestory等,反射注入对象给属性或方法参数
			populateBean(beanName, mbd, instanceWrapper);

			// 4、初始化
			// 配置的初始化方法调用:
			// 		InitializingBean接口afterPropertiesSet方法
			// 		@PostConstruct注解下的方法
			// 包含AOP入口
			exposedObject = initializeBean(beanName, exposedObject, mbd);
		}
		catch (Throwable ex) {
			if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
				throw (BeanCreationException) ex;
			}
			else {
				throw new BeanCreationException(
						mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
			}
		}

		if (earlySingletonExposure) {
			Object earlySingletonReference = getSingleton(beanName, false);
			if (earlySingletonReference != null) {
				if (exposedObject == bean) {
					exposedObject = earlySingletonReference;
				}
				else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
					String[] dependentBeans = getDependentBeans(beanName);
					Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
					for (String dependentBean : dependentBeans) {
						if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
							actualDependentBeans.add(dependentBean);
						}
					}
					if (!actualDependentBeans.isEmpty()) {
						throw new BeanCurrentlyInCreationException(beanName,
								"Bean with name '" + beanName + "' has been injected into other beans [" +
								StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
								"] in its raw version as part of a circular reference, but has eventually been " +
								"wrapped. This means that said other beans do not use the final version of the " +
								"bean. This is often the result of over-eager type matching - consider using " +
								"'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example.");
					}
				}
			}
		}

		// Register bean as disposable.
		try {
			// 注册bean销毁时的类 DisposableBeanAdapter
			registerDisposableBeanIfNecessary(beanName, bean, mbd);
		}
		catch (BeanDefinitionValidationException ex) {
			throw new BeanCreationException(
					mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
		}

		return exposedObject;
	}

org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#applyMergedBeanDefinitionPostProcessors

protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName) {
		for (BeanPostProcessor bp : getBeanPostProcessors()) {
			if (bp instanceof MergedBeanDefinitionPostProcessor) {
				MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;
				bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
			}
		}
	}

org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor#postProcessMergedBeanDefinition

public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
		InjectionMetadata metadata = findAutowiringMetadata(beanName, beanType, null);
		metadata.checkConfigMembers(beanDefinition);
	}

org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor#findAutowiringMetadata 从这里开始找注入点

private InjectionMetadata findAutowiringMetadata(String beanName, Class<?> clazz, @Nullable PropertyValues pvs) {

		// 先尝试从缓存中查找,cacheKey为beanName或类名
		// 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);
					}
					// 解析后放入缓存
					metadata = buildAutowiringMetadata(clazz);
					this.injectionMetadataCache.put(cacheKey, metadata);
				}
			}
		}
		return metadata;
	}

org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor#buildAutowiringMetadata 将封装有注入属性的列表一起封装到InjectionMetadata中

private InjectionMetadata buildAutowiringMetadata(final Class<?> clazz) {
		// 存放解析好的属性信息
		if (!AnnotationUtils.isCandidateClass(clazz, this.autowiredAnnotationTypes)) {
			return InjectionMetadata.EMPTY;
		}

		List<InjectionMetadata.InjectedElement> elements = new ArrayList<>();
		Class<?> targetClass = clazz;

		// Spring会一直递归向上遍历bean的父类
		do {
			// 存放当前解析的类中带有注解的属性
			final List<InjectionMetadata.InjectedElement> currElements = new ArrayList<>();

			// doWithLocalFields方法中,其实就是获取class的所有字段,对每个字段调用FieldCallback方法
			ReflectionUtils.doWithLocalFields(targetClass, field -> {
				MergedAnnotation<?> ann = findAutowiredAnnotation(field);
				if (ann != null) {
					if (Modifier.isStatic(field.getModifiers())) {
						if (logger.isInfoEnabled()) {
							logger.info("Autowired annotation is not supported on static fields: " + field);
						}
						return;
					}
					// 如果注解中存在required属性,获取属性的值,并保存起来
					// 如果不存在required属性则默认为true
					boolean required = determineRequiredStatus(ann);

					// 使用AutowiredFieldElement类型,将字段信息封装起来
					currElements.add(new AutowiredFieldElement(field, required));
				}
			});

			// 与Field逻辑相同,都是遍历所有声明的方法,判断是否带有特定的注解
			// 如果存在注解标注的方法,并使用AutowiredMethodElement封装起来
			ReflectionUtils.doWithLocalMethods(targetClass, method -> {
				Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
				if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) {
					return;
				}
				MergedAnnotation<?> ann = findAutowiredAnnotation(bridgedMethod);
				if (ann != null && method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) {
					if (Modifier.isStatic(method.getModifiers())) {
						if (logger.isInfoEnabled()) {
							logger.info("Autowired annotation is not supported on static methods: " + method);
						}
						return;
					}
					if (method.getParameterCount() == 0) {
						if (logger.isInfoEnabled()) {
							logger.info("Autowired annotation should only be used on methods with parameters: " +
									method);
						}
					}
					boolean required = determineRequiredStatus(ann);
					// 与field不同的一点就是,AutowiredMethodElement会获取属性描述符,一起封装
					PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
					currElements.add(new AutowiredMethodElement(method, required, pd));
				}
			});

			elements.addAll(0, currElements);
			targetClass = targetClass.getSuperclass();
		}
		// Spring会一直递归向上遍历bean的父类
		while (targetClass != null && targetClass != Object.class);

		// 将封装有注入属性的列表一起封装到InjectionMetadata中
		return InjectionMetadata.forElements(elements, clazz);
	}

org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#populateBean 填充属性

protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
		// 传入的beanWrapper为空,如果属性不为空就抛出异常,否则返回null
		if (bw == null) {
			if (mbd.hasPropertyValues()) {
				throw new BeanCreationException(
						mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
			}
			else {
				// Skip property population phase for null instance.
				return;
			}
		}

		// 应用后处理器InstantiationAwareBeanPostProcessor,调用其postProcessAfterInstantiation方法
		// 在注入属性前修改bean状态,如果方法中发挥false的话,可以终止后面代码运行,直接返回
		// Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
		// state of the bean before properties are set. This can be used, for example,
		// to support styles of field injection.
		if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
			for (BeanPostProcessor bp : getBeanPostProcessors()) {
				if (bp instanceof InstantiationAwareBeanPostProcessor) {
					InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
					if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
						return;
					}
				}
			}
		}

		// 是否在BeanDefinition中设置了属性值
		PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);

		// 为bean注入PropertyValues中包含的属性
		// 这种注入方式适用的是配置文件中通过<property>配置的属性并且显示在配置文件中配置了autowireMode属性
		int resolvedAutowireMode = mbd.getResolvedAutowireMode();
		if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {

			// by_name是根据属性名字找bean
			// by_type是根据属性所对应的set方法的参数类型找bean
			// 找到bean之后都需要调用set方法进行注入
			MutablePropertyValues newPvs = new MutablePropertyValues(pvs);

			// Add property values based on autowire by name if applicable.
			if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
				// 根据名称自动注入
				autowireByName(beanName, mbd, bw, newPvs);
			}
			// Add property values based on autowire by type if applicable.
			if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
				// 根据类型自动注入
				autowireByType(beanName, mbd, bw, newPvs);
			}
			pvs = newPvs;

			// 注意:执行完这里的代码之后,这只是把属性以及找到的值存在了pvs里面,并没有完成反射赋值
		}

		// 执行完spring的自动注入之后,就开始解析@Autowired,这里叫做实例化回调
		boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
		boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);

		// @Autowired注解的 AutowiredAnnotationBeanPostProcessor
		// @Resource注解的 CommonAnnotationBeanPostProcessor
		PropertyDescriptor[] filteredPds = null;

		// 如果存在InstantiationAwareBeanPostProcessor后处理器
		if (hasInstAwareBpps) {
			if (pvs == null) {
				pvs = mbd.getPropertyValues();
			}
			for (BeanPostProcessor bp : getBeanPostProcessors()) {
				if (bp instanceof InstantiationAwareBeanPostProcessor) {
					InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;

					// 调用BeanPostProcessor分别解析 @Autowired   @Resource   @Value 得到属性值
					// 应用后处理器InstantiationAwareBeanPostProcessor,调用其postProcessPropertyValues方法
					// 作用是对需要进行依赖检查的属性进行处理
					// Autowired等注解的属性就是在这里完成注入的
					PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
					if (pvsToUse == null) {
						if (filteredPds == null) {
							filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
						}

						// TODO Autowired注解的属性注入
						// InstantiationAwareBeanPostProcessor 后处理器的postProcessPropertyValues方法
						// 重点需要关注的有以下几个实现类:

						// RequiredAnnotationBeanPostProcessor:检查属性的setter方法上是否标注有@Required注解,如果带有此注解,
						// 		但是未配置属性(配置文件中的<property>元素),那么就会抛出异常
						// AutowiredAnnotationBeanPostProcessor:遍历bean的Field属性,寻找标注有@Autowired和@Value注解的字段,
						// 		并完成属性注入(如果能加载到javax.inject.Inject注解的话,也会扫描该注解)
						// CommonAnnotationBeanPostProcessor:遍历bean的字段,寻找通用的依赖(javax中规定的)注解,完成属性注入。
						// 		通用注解包括有:javax.annotation.Resource,javax.xml.ws.WebServiceRef,javax.ejb.EJB。
						pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);

						// 返回值为null时会属性的填充,直接返回
						if (pvsToUse == null) {
							return;
						}
					}
					pvs = pvsToUse;
				}
			}
		}
		// 需要进行依赖检查
		if (needsDepCheck) {
			if (filteredPds == null) {
				filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
			}
			checkDependencies(beanName, mbd, filteredPds, pvs);
		}

		// 注入配置文件中<property>配置的属性
		if (pvs != null) {
			// 配置文件的属性注入
			// 对于通过配置文件中给<bean>配置<property>节点来完成注入的代码实现在applyPropertyValues中
			applyPropertyValues(beanName, mbd, bw, pvs);
		}
	}

org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor#postProcessProperties

public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
		// 遍历获取带有自动注入注解的字段和方法,并且将字段信息、注解信息
		// 注解包括:@Value、@Autowired、@Inject(javax.inject.Inject,如果能加载到这个类的话)
		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;
	}

org.springframework.beans.factory.annotation.InjectionMetadata#inject

public void inject(Object target, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
		Collection<InjectedElement> checkedElements = this.checkedElements;
		Collection<InjectedElement> elementsToIterate =
				(checkedElements != null ? checkedElements : this.injectedElements);
		if (!elementsToIterate.isEmpty()) {
			for (InjectedElement element : elementsToIterate) {
				// 遍历先前解析好的AutowiredFieldElement或AutowiredMethodElement,调用其inject方法
				// org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.AutowiredFieldElement.inject
				element.inject(target, beanName, pvs);
			}
		}
	}

org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.AutowiredFieldElement#inject 这里以字段注入为例

protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {

			// AutowiredFieldElement中保存的是Field对象,如果是AutowiredMethodElement则会保存Method对象
			Field field = (Field) this.member;

			// 最终需要注入的值
			Object value;

			// 如果已经被缓存过,就可以从缓存中获取
			if (this.cached) {
				value = resolvedCachedArgument(beanName, this.cachedFieldValue);
			}
			else {
				// 使用DependencyDescriptor封装Field
				// 其属性包括:field:Field对象,declaringClass:Field所在类,fieldName:字段名
				// required:是否允许为空,eager:是否懒加载(注解标注的字段都为false)
				DependencyDescriptor desc = new DependencyDescriptor(field, this.required);
				desc.setContainingClass(bean.getClass());
				Set<String> autowiredBeanNames = new LinkedHashSet<>(1);
				Assert.state(beanFactory != null, "No BeanFactory available");
				TypeConverter typeConverter = beanFactory.getTypeConverter();
				try {
					// TODO 所谓的循环依赖
					// 通过BeanFactory根据DependencyDescriptor信息解决依赖
					value = beanFactory.resolveDependency(desc, beanName, autowiredBeanNames, typeConverter);
				}
				catch (BeansException ex) {
					throw new UnsatisfiedDependencyException(null, beanName, new InjectionPoint(field), ex);
				}
				synchronized (this) {
					// 将解析结果放入缓存
					if (!this.cached) {
						Object cachedFieldValue = null;
						if (value != null || this.required) {
							cachedFieldValue = desc;
							// 在BeanFactory中注册依赖关系
							registerDependentBeans(beanName, autowiredBeanNames);
							// 如果与属性类型相同的注入bean只有一个,那么就可以设置到缓存中
							if (autowiredBeanNames.size() == 1) {
								String autowiredBeanName = autowiredBeanNames.iterator().next();
								if (beanFactory.containsBean(autowiredBeanName) &&
										beanFactory.isTypeMatch(autowiredBeanName, field.getType())) {
									cachedFieldValue = new ShortcutDependencyDescriptor(
											desc, autowiredBeanName, field.getType());
								}
							}
						}
						this.cachedFieldValue = cachedFieldValue;
						this.cached = true;
					}
				}
			}
			// 通过Field对象的反射,将值设置到bean中
			if (value != null) {
				ReflectionUtils.makeAccessible(field);
				field.set(bean, value);
			}
		}

org.springframework.beans.factory.support.DefaultListableBeanFactory#resolveDependency

public Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName,
			@Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {

		descriptor.initParameterNameDiscovery(getParameterNameDiscoverer());

		// 对于Java8中Optional类的处理
		if (Optional.class == descriptor.getDependencyType()) {
			return createOptionalDependency(descriptor, requestingBeanName);
		}
		// 对于前面讲到的提早曝光的ObjectFactory的特殊处理
		else if (ObjectFactory.class == descriptor.getDependencyType() ||
				ObjectProvider.class == descriptor.getDependencyType()) {
			return new DependencyObjectProvider(descriptor, requestingBeanName);
		}
		// javaxInjectProviderClass的特殊处理
		else if (javaxInjectProviderClass == descriptor.getDependencyType()) {
			return new Jsr330Factory().createDependencyProvider(descriptor, requestingBeanName);
		}
		else {
			// 如果字段上带有@Lazy注解,表示进行懒加载
			// Spring不会立即创建注入属性的实例,而是生成代理对象,来代替实例
			Object result = getAutowireCandidateResolver().getLazyResolutionProxyIfNecessary(
					descriptor, requestingBeanName);
			if (result == null) {
				// 通用处理逻辑
				result = doResolveDependency(descriptor, requestingBeanName, autowiredBeanNames, typeConverter);
			}
			return result;
		}
	}

org.springframework.beans.factory.support.DefaultListableBeanFactory#doResolveDependency

public Object doResolveDependency(DependencyDescriptor descriptor, @Nullable String beanName,
			@Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {

		InjectionPoint previousInjectionPoint = ConstructorResolver.setCurrentInjectionPoint(descriptor);
		try {
			// Spring在第一次创建依赖的bean时,会保存该bena的beanName作为shortcut
			// 在第二次创建时,就可以直接根据beanName调用getBean方法,不需要再根据类型来重新查询一遍
			Object shortcut = descriptor.resolveShortcut(this);
			if (shortcut != null) {
				return shortcut;
			}

			// 注入属性的类型
			Class<?> type = descriptor.getDependencyType();

			// 处理@Value注解-------------------------------------
			// 获取@Value中的value属性
			Object value = getAutowireCandidateResolver().getSuggestedValue(descriptor);
			if (value != null) {
				// 解析value
				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());
				try {
					// 如果需要会进行类型转换后返回结果
					return converter.convertIfNecessary(value, type, descriptor.getTypeDescriptor());
				}
				catch (UnsupportedOperationException ex) {
					// A custom TypeConverter which does not support TypeDescriptor resolution...
					return (descriptor.getField() != null ?
							converter.convertIfNecessary(value, type, descriptor.getField()) :
							converter.convertIfNecessary(value, type, descriptor.getMethodParameter()));
				}
			}

			// 对数组、容器类型的处理
			// 因为是数组或容器,Sprng可以直接把符合类型的bean都注入到数组或容器中,处理逻辑是:
			// 1.确定容器或数组的组件类型
			// 2.调用findAutowireCandidates方法,获取与组件类型匹配的Map(beanName -> bean实例)
			// 3.将符合beanNames添加到autowiredBeanNames中
			Object multipleBeans = resolveMultipleBeans(descriptor, beanName, autowiredBeanNames, typeConverter);
			if (multipleBeans != null) {
				return multipleBeans;
			}

			// 对非数组、容器对象的处理
			// 获取所有类型匹配的Map(beanName -> bean实例)
			Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, descriptor);

			// 结果为空
			if (matchingBeans.isEmpty()) {
				// 如果配置了required属性为true(默认值也是true)的话,抛出异常
				if (isRequired(descriptor)) {
					raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor);
				}
				return null;
			}

			String autowiredBeanName;
			Object instanceCandidate;

			// 如果类型匹配的bean不止一个,Spring需要进行筛选,筛选失败的话抛出异常
			if (matchingBeans.size() > 1) {
				autowiredBeanName = determineAutowireCandidate(matchingBeans, descriptor);
				if (autowiredBeanName == null) {
					if (isRequired(descriptor) || !indicatesMultipleBeans(type)) {
						return descriptor.resolveNotUnique(descriptor.getResolvableType(), matchingBeans);
					}
					else {
						// In case of an optional Collection/Map, silently ignore a non-unique case:
						// possibly it was meant to be an empty collection of multiple regular beans
						// (before 4.3 in particular when we didn't even look for collection beans).
						return null;
					}
				}
				instanceCandidate = matchingBeans.get(autowiredBeanName);
			}
			else {
				// 只有一个bean与类型匹配,那么直接使用该bean
				// We have exactly one match.
				Map.Entry<String, Object> entry = matchingBeans.entrySet().iterator().next();
				autowiredBeanName = entry.getKey();
				instanceCandidate = entry.getValue();
			}

			if (autowiredBeanNames != null) {
				autowiredBeanNames.add(autowiredBeanName);
			}

			// 如果获取到instanceCandidate是Class类型
			// 那么还需要beanFactory.getBean(autowiredBeanName, instanceCandidate)来获取bean的实例
			// 否则直接返回bean
			if (instanceCandidate instanceof Class) {
				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);
		}
	}

org.springframework.beans.factory.support.DefaultListableBeanFactory#determineAutowireCandidate 找到多个bean的情况下

protected String determineAutowireCandidate(Map<String, Object> candidates, DependencyDescriptor descriptor) {
		Class<?> requiredType = descriptor.getDependencyType();

		// 处理@Primary
		String primaryCandidate = determinePrimaryCandidate(candidates, requiredType);
		if (primaryCandidate != null) {
			return primaryCandidate;
		}

		// 处理@Priority
		String priorityCandidate = determineHighestPriorityCandidate(candidates, requiredType);
		if (priorityCandidate != null) {
			return priorityCandidate;
		}

		// Fallback
		for (Map.Entry<String, Object> entry : candidates.entrySet()) {
			String candidateName = entry.getKey();
			Object beanInstance = entry.getValue();
			if ((beanInstance != null && this.resolvableDependencies.containsValue(beanInstance)) ||
					matchesBeanName(candidateName, descriptor.getDependencyName())) {
				return candidateName;
			}
		}
		return null;
	}

org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.AutowiredFieldElement#inject 最后就是反射给属性赋值

if (value != null) {
				ReflectionUtils.makeAccessible(field);
				field.set(bean, value);
			}

贴过程分析

AbstractAutowireCapableBeanFactory#doCreateBean
	AbstractAutowireCapableBeanFactory#applyMergedBeanDefinitionPostProcessors
		AutowiredAnnotationBeanPostProcessor#postProcessMergedBeanDefinition 寻找注入点@Autowired、@Value、@Inject
			AutowiredAnnotationBeanPostProcessor#findAutowiringMetadata
				AutowiredAnnotationBeanPostProcessor#buildAutowiringMetadata
					findAutowiredAnnotation
						AutowiredAnnotationBeanPostProcessor#findAutowiredAnnotation
					把要注入的字段和方法都封装为InjectedElement,然后统一放到一个集合中
					
	populateBean 填充属性
		getPropertyValues 获取属性值
			遍历所有的BeanPostProcessors
				postProcessProperties
					AutowiredAnnotationBeanPostProcessor#postProcessProperties
						inject
							AutowiredAnnotationBeanPostProcessor.AutowiredMethodElement#inject 方法注入
							AutowiredAnnotationBeanPostProcessor.AutowiredFieldElement#inject 字段注入
								DefaultListableBeanFactory#resolveDependency
									Optional
									Lazy 如果依赖描述上有Lazy则生成代理对象,在调用代理对象方法时才执行下面的方法
									ObjectFactory 在调用getObject方法时在执行下面的方法
										DefaultListableBeanFactory#doResolveDependency
											是否存在@Value
												如果存在则解析descriptor上的@Value并返回
												如果不存在则判断descriptor的类型
													resolveMultipleBeans
														如果是map就直接返回
														如果是Collection则调用findAutowireCandidates将map的values返回
															findAutowireCandidates(beanName, type, descriptor) 根据type有没有找到bean
																如果没找到
																	isRequired
																		true 报错
																		false 返回null
																如果找到了
																	只有一个 直接返回该bean,如果是class则调用getBean生成该bean对象
																		descriptor.resolveCandidate
																	有多个 
																		从多个bean中选出被@Primary标注的bean,如果找出多个则报错
																			如果没有被@Primary标注
																				检查是否被@Priority定义优先级,如果有就找出优先级最高的bean,
																				如果没有优先级:descriptor.getDependencyName() 找出唯一的bean
																					是否找到了唯一的bean
																						找到就返回该bean,如果是class则调用getBean生成该bean对象
																							descriptor.resolveCandidate
																						未找到
																							isRequired
																								true 报错
																								false 返回null

spring有5中注入模型:byType、byName、constructor、defalut、no,我们平时用的@Autowire都属于默认注入,如果想验证其他方式可以通过xml的方式进行测试

<bean name="userService" class="com.spring.service.UserService" autowire="constructor">

 

补充:

@Resource 原理,先找注入点,注入之前先判断beanFactory中是否存在注入点名字对应的bean,如果存在就按名字去找bean,找不到就报错;如果不存在则检查@Resource注解中是否指定了name属性,如果指定了就按name去找bean,如果没指定就和@Autowired一样先byType再byName。

 

1、开始bean实例化过程中,在填充属性之前先找到加了@Autowire和@Value的注入点,封装为

InjectedElement保存到 injectedElements 集合中。

2、开始填充属性,先获取所有的属性,执行bean的后置处理器AutowiredAnnotationBeanPostProcessor,按照字段注入或者方法注入的方式进行注入。

3、非懒加载的情况下,检查是否存在@Value,处理数组类型,处理非数组类型。经过上面处理如

果得到bean的数量为1就直接返回,如果大于1就检查@Primary,如果有多个bean都加了

@Primary就报错,然后再检查@Priority的优先级,值越小优先级越高,如果找到了返回这个

bean,如果bean类型是class就调用getBean方法生成该bean对象。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值