【04】spring源碼解析之Autowired屬性注入

    在文章【03】spring源碼解析之配置文件context:component-scan 解析流程中分析了spring是如何解析配置文件的,spring根據配置文件中配置的bean掃描路徑(或者是xml文件中配置的bean)找到這些須要被spring管理的bean,找到這些bean之後,並無組織這些bean之間的關係,只是返回了BeanDefinitions,也就是描述這些Bean性質的BeanDefinition列表,對於一個Bean做爲另一個Bean的屬性是如何注入的則在其餘的流程中進行組裝。下圖的時序圖粗略的描述了一下整個注入的過程 java



從上圖能夠看出,Bean組裝的入口是AbstractApplicationContext 的registerBeanPostProcessors方法,這個方法接受一個ConfigurableListableBeanFactory做爲參數,對於ConfigurableListableBeanFactory類的層級關係以下類圖: spring


從關係圖中能夠看出,ConfigurableListableBeanFactory繼承ListableBeanFactory,ListableBeanFactory持有BeanDefinition對象,也就是說ConfigurableListableBeanFactory在解析的時候持有了BeanDefinitions這些對象。 app

 

從圖時序圖1中能夠看出,Bean的建立關鍵代碼是AbstractAutowireCapableBeanFactory的doCreateBean方法,而進行屬性注入的是populateBean方法,這個方法聲明以下: ide

protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args); 函數


它接收三個參數,第一個參數是bean的名稱,第二個是對這個類的描述對象,第三個參數是建立這個bean時候的構造函數所須要的參數。返回值是一個建立完成的對象。 post


而建立對象的過程主要是分爲兩個步驟 ui

一、建立對象 this

二、注入屬性 lua

建立對象是由createBeanInstance方法完成的,注入屬性是populateBean方法完成的 spa

1、對象建立

protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, Object[] args) {
   // 確保這個類是存在的,而且經過mbd反向查找到類
   Class<?> beanClass = resolveBeanClass(mbd, beanName);

   //校驗類是否爲空,是否public的,是否可訪問的,若是不知足以上條件,則拋出異常
   if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {
      throw new BeanCreationException(mbd.getResourceDescription(), beanName,
            "Bean class isn't public, and non-public access not allowed: " + beanClass.getName());
   }

   .....

   //實例化Bean,對具備沒有參數的構造函數進行實例化,registerCustomEditors
    //調用過程爲instantiateBean->registerCustomEditors->BeanUtils.instantiateClass(editorClass);  

   return instantiateBean(beanName, mbd);
}

//把instanceWrapper 對象轉化爲真正實例化後的對象
final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null);



2、屬性注入

一、查找Bean中的註解

入口爲applyMergedBeanDefinitionPostProcessors,真正的查找方法爲AutowiredAnnotationBeanProcessor中的findAutowiredMetadata方法,而後調用bulidResourceMetadate方法,解析class文件中的註解文件,

private InjectionMetadata buildAutowiringMetadata(final Class<?> clazz) {
		LinkedList<InjectionMetadata.InjectedElement> elements = new LinkedList<InjectionMetadata.InjectedElement>();
		Class<?> targetClass = clazz;

		do {
			final LinkedList<InjectionMetadata.InjectedElement> currElements =
					new LinkedList<InjectionMetadata.InjectedElement>();
			
			//經過反射的方法,找到class的全部屬性,而後回調FieldCallback方法,在這個方法中過濾被Autowired註解所修飾
			的屬性,而且校驗屬性是否是static的,若是是的話,則記錄warin級別的日誌,Autowired不支持修飾static變量
			而後把符合條件的屬性集合放入到currElements集合中以待後續處理
			ReflectionUtils.doWithLocalFields(targetClass, new ReflectionUtils.FieldCallback() {
				@Override
				public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
					AnnotationAttributes ann = findAutowiredAnnotation(field);
					if (ann != null) {
						if (Modifier.isStatic(field.getModifiers())) {
							if (logger.isWarnEnabled()) {
								logger.warn("Autowired annotation is not supported on static fields: " + field);
							}
							return;
						}
						boolean required = determineRequiredStatus(ann);
						currElements.add(new AutowiredFieldElement(field, required));
					}
				}
			});


			//和doWithLocalFields採起相同的方式,處理相關方法
			ReflectionUtils.doWithLocalMethods(targetClass, new ReflectionUtils.MethodCallback() {
				@Override
				public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
					Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
					if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) {
						return;
					}
					AnnotationAttributes ann = findAutowiredAnnotation(bridgedMethod);
					if (ann != null && method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) {
						if (Modifier.isStatic(method.getModifiers())) {
							if (logger.isWarnEnabled()) {
								logger.warn("Autowired annotation is not supported on static methods: " + method);
							}
							return;
						}
						if (method.getParameterTypes().length == 0) {
							if (logger.isWarnEnabled()) {
								logger.warn("Autowired annotation should be used on methods with parameters: " + method);
							}
						}
						boolean required = determineRequiredStatus(ann);
						PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
						currElements.add(new AutowiredMethodElement(method, required, pd));
					}
				}
			});

			elements.addAll(0, currElements);
			targetClass = targetClass.getSuperclass();
		}
		while (targetClass != null && targetClass != Object.class);

		return new InjectionMetadata(clazz, elements);
	}



二、屬性註解檢驗

static修飾的屬性,不容許使用Autowired註解



三、屬性注入

數據準備完成之後,經過調用populateBean方法,真正的對須要注入的屬性進行注入

protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) {
		PropertyValues pvs = mbd.getPropertyValues();

		if (bw == null) {
			if (!pvs.isEmpty()) {
				throw new BeanCreationException(
						mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
			}
			else {
				// Skip property population phase for null instance.
				return;
			}
		}

		// 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.
		boolean continueWithPropertyPopulation = true;

		if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
			for (BeanPostProcessor bp : getBeanPostProcessors()) {
				if (bp instanceof InstantiationAwareBeanPostProcessor) {
					InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
					if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
						continueWithPropertyPopulation = false;
						break;
					}
				}
			}
		}

		if (!continueWithPropertyPopulation) {
			return;
		}

//mbd.getResolvedAutowireMode() 根據自動注入策略,獲取注入策略的值,默認值是0
RootBeanDefinition.AUTOWIRE_BY_NAME的值是1
RootBeanDefinition.AUTOWIRE_BY_TYPE的值是2

		if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME ||
				mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
			MutablePropertyValues newPvs = new MutablePropertyValues(pvs);

			// Add property values based on autowire by name if applicable.
			if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) {
				autowireByName(beanName, mbd, bw, newPvs);
			}

			// Add property values based on autowire by type if applicable.
			if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
				autowireByType(beanName, mbd, bw, newPvs);
			}

			pvs = newPvs;
		}

		boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
		boolean needsDepCheck = (mbd.getDependencyCheck() != RootBeanDefinition.DEPENDENCY_CHECK_NONE);

		if (hasInstAwareBpps || needsDepCheck) {
			PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
			if (hasInstAwareBpps) {
				for (BeanPostProcessor bp : getBeanPostProcessors()) {
					if (bp instanceof InstantiationAwareBeanPostProcessor) {
						InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
						pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
						if (pvs == null) {
							return;
						}
					}
				}
			}
			if (needsDepCheck) {
				checkDependencies(beanName, mbd, filteredPds, pvs);
			}
		}

		applyPropertyValues(beanName, mbd, bw, pvs);
	}
實例化屬性,注入的代碼
	
	DefaultListableBeanFactory.java
	
	public Object doResolveDependency(DependencyDescriptor descriptor, String beanName,
			Set<String> autowiredBeanNames, TypeConverter typeConverter) throws BeansException {

		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()));
		}

		if (type.isArray()) {
			Class<?> componentType = type.getComponentType();
			DependencyDescriptor targetDesc = new DependencyDescriptor(descriptor);
			targetDesc.increaseNestingLevel();
			
			
			Map<String, Object> matchingBeans = findAutowireCandidates(beanName, componentType, targetDesc);
			//注入其依賴的屬性,實例化屬性,這樣就能達到一個循環,把全部的依賴從最裏層逐步剝離出來進行實例化,而後注入
			
			if (matchingBeans.isEmpty()) {
				if (descriptor.isRequired()) {
					raiseNoSuchBeanDefinitionException(componentType, "array of " + componentType.getName(), descriptor);
				}
				return null;
			}
			if (autowiredBeanNames != null) {
				autowiredBeanNames.addAll(matchingBeans.keySet());
			}
			TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter());
			Object result = converter.convertIfNecessary(matchingBeans.values(), type);
			if (getDependencyComparator() != null && result instanceof Object[]) {
				Arrays.sort((Object[]) result, adaptDependencyComparator(matchingBeans));
			}
			return result;
		}
		else if (Collection.class.isAssignableFrom(type) && type.isInterface()) {
			Class<?> elementType = descriptor.getCollectionType();
			if (elementType == null) {
				if (descriptor.isRequired()) {
					throw new FatalBeanException("No element type declared for collection [" + type.getName() + "]");
				}
				return null;
			}
			DependencyDescriptor targetDesc = new DependencyDescriptor(descriptor);
			targetDesc.increaseNestingLevel();
			Map<String, Object> matchingBeans = findAutowireCandidates(beanName, elementType, targetDesc);
			if (matchingBeans.isEmpty()) {
				if (descriptor.isRequired()) {
					raiseNoSuchBeanDefinitionException(elementType, "collection of " + elementType.getName(), descriptor);
				}
				return null;
			}
			if (autowiredBeanNames != null) {
				autowiredBeanNames.addAll(matchingBeans.keySet());
			}
			TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter());
			Object result = converter.convertIfNecessary(matchingBeans.values(), type);
			if (getDependencyComparator() != null && result instanceof List) {
				Collections.sort((List<?>) result, adaptDependencyComparator(matchingBeans));
			}
			return result;
		}
		else if (Map.class.isAssignableFrom(type) && type.isInterface()) {
			Class<?> keyType = descriptor.getMapKeyType();
			if (String.class != keyType) {
				if (descriptor.isRequired()) {
					throw new FatalBeanException("Key type [" + keyType + "] of map [" + type.getName() +
							"] must be [java.lang.String]");
				}
				return null;
			}
			Class<?> valueType = descriptor.getMapValueType();
			if (valueType == null) {
				if (descriptor.isRequired()) {
					throw new FatalBeanException("No value type declared for map [" + type.getName() + "]");
				}
				return null;
			}
			DependencyDescriptor targetDesc = new DependencyDescriptor(descriptor);
			targetDesc.increaseNestingLevel();
			Map<String, Object> matchingBeans = findAutowireCandidates(beanName, valueType, targetDesc);
			if (matchingBeans.isEmpty()) {
				if (descriptor.isRequired()) {
					raiseNoSuchBeanDefinitionException(valueType, "map with value type " + valueType.getName(), descriptor);
				}
				return null;
			}
			if (autowiredBeanNames != null) {
				autowiredBeanNames.addAll(matchingBeans.keySet());
			}
			return matchingBeans;
		}
		else {
			Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, descriptor);
			if (matchingBeans.isEmpty()) {
				if (descriptor.isRequired()) {
					raiseNoSuchBeanDefinitionException(type, "", descriptor);
					
					//若是沒有找到屬性所要注入的實例,則會拋出咱們很是常見的一個異常 ^_^
				//expected at least 1 bean which qualifies as autowire candidate for this dependency.  Dependency annotations:xxxx
				}
				return null;
			}
			if (matchingBeans.size() > 1) {
				String primaryBeanName = determineAutowireCandidate(matchingBeans, descriptor);
				if (primaryBeanName == null) {
					throw new NoUniqueBeanDefinitionException(type, matchingBeans.keySet());
					//針對一個屬性,找到了多個實例,拋出實例重複異常
					//expected at least 1 bean which qualifies as autowire candidate for this dependency.
				}
				if (autowiredBeanNames != null) {
					autowiredBeanNames.add(primaryBeanName);
				}
				return matchingBeans.get(primaryBeanName);
			}
			//確保有且只能找到一個
			// We have exactly one match.
			Map.Entry<String, Object> entry = matchingBeans.entrySet().iterator().next();
			if (autowiredBeanNames != null) {
				autowiredBeanNames.add(entry.getKey());
			}
			return entry.getValue();
		}
	}


最讓人興奮的地方來了,對象屬性值注入的最根本的代碼


AutowiredAnnotationBeanPostProcessor的內部類AutowiredFieldElement中的inject方法

 @Override
protected void inject(Object bean, String beanName, PropertyValues pvs) throws Throwable {
                ...........
		...............
		if (value != null) {
					ReflectionUtils.makeAccessible(field);
					field.set(bean, value);
					//對屬性注入值的最根本的代碼
					//注入屬性^_^ ^_^ ^_^^_^^_^^_^^_^^_^^_^ 
					//我得意的笑啊,終於找到這傢伙了
					
				}
			}
			catch (Throwable ex) {
				throw new BeanCreationException("Could not autowire field: " + field, ex);
			}
		}
	}
相關文章
相關標籤/搜索