天天看點

【Spring源碼--IOC容器的實作】(六)Bean的依賴注入

前言:

1.上一篇文章已經分析bean對象的生成,在此基礎上,本文将分析Spring怎麼把這些bean對象的依賴關系設定好,完成依賴注入的過程。 2.依賴注入的過程大緻可以分為兩部分:(1).bean屬性的解析;(2).bean屬性的注入。 3.依賴注入很多内容都是從BeanDefinition中取到的,是以BeanDefinition的載入和解析非常重要,最好結合着前面的文章一塊看。 【SpringIOC源碼--IOC容器實作】(三)BeanDefinition的載入和解析【I】、 【SpringIOC源碼--IOC容器實作】(三)BeanDefinition的載入和解析【II】。

Bean的依賴注入

Bean屬性的解析

在讨論Bean的依賴注入時,我們先回到AbstractAutowireCapableBeanFactory類的doCreateBean方法。在這裡我們有兩個方法,一個是createBeanInstance生成對象,一個是populateBean對象執行個體化,也就是我們要的依賴注入,來看下簡略代碼: 代碼1.1:AbstractAutowireCapableBeanFactory類的doCreateBean方法:

protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) {
		BeanWrapper instanceWrapper = null;
		...
		if (instanceWrapper == null) {
			instanceWrapper = createBeanInstance(beanName, mbd, args);
		}
		...
		
		Object exposedObject = bean;
		try {
			populateBean(beanName, mbd, instanceWrapper);
			if (exposedObject != null) {
				exposedObject = initializeBean(beanName, exposedObject, mbd);
			}
		}
		...

		return exposedObject;
	}
           

代碼我們已經找到了,現在就進入populateBean方法具體來看看其實作: 代碼1.2:AbstractAutowireCapableBeanFactory類的populateBean方法:

protected void populateBean(String beanName, AbstractBeanDefinition mbd, BeanWrapper bw) {
		//擷取容器在解析Bean定義的時候的屬性值  
		PropertyValues pvs = mbd.getPropertyValues();

		if (bw == null) {
			if (!pvs.isEmpty()) {
				throw new BeanCreationException(
						mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
			}
			else {
				//執行個體對象為null,屬性值也為空,不需要設定屬性值,直接傳回
				return;
			}
		}

		//在設定屬性之前調用Bean的PostProcessor後置處理器
		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;
		}
		
		//依賴注入開始,首先處理autowire自動裝配的注入  
		if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME ||
				mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
			MutablePropertyValues newPvs = new MutablePropertyValues(pvs);

			//對autowire自動裝配的處理,根據Bean名稱自動裝配注入
			if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) {
				autowireByName(beanName, mbd, bw, newPvs);
			}

			//根據Bean類型自動裝配注入
			if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
				autowireByType(beanName, mbd, bw, newPvs);
			}

			pvs = newPvs;
		}
		
		//檢查容器是否持有用于處理單态模式Bean關閉時的後置處理器 
		boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
		//Bean執行個體對象沒有依賴,即沒有繼承基類 
		boolean needsDepCheck = (mbd.getDependencyCheck() != RootBeanDefinition.DEPENDENCY_CHECK_NONE);
		
		if (hasInstAwareBpps || needsDepCheck) {
			//從執行個體對象中提取屬性描述符
			PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw);
			if (hasInstAwareBpps) {
				for (BeanPostProcessor bp : getBeanPostProcessors()) {
					if (bp instanceof InstantiationAwareBeanPostProcessor) {
						InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
						//使用BeanPostProcessor處理器處理屬性值 
						pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
						if (pvs == null) {
							return;
						}
					}
				}
			}
			if (needsDepCheck) {
				//為要設定的屬性進行依賴檢查  
				checkDependencies(beanName, mbd, filteredPds, pvs);
			}
		}
		//對屬性進行注入
		applyPropertyValues(beanName, mbd, bw, pvs);
	}
           

看這塊代碼有幾點我們要明确:

  • 這裡包括後面所講的内容:全部是bean在xml中的定義的内容,我們平時用的@Resource @Autowired并不是在這裡解析的,那些屬于Spring注解的内容。
  • 這裡的autowire跟@Autowired不一樣,autowire是Spring配置檔案中的一個配置,@Autowired是一個注解。
    <bean id="personFactory" class="com.xx.PersonFactory" autowire="byName">
               
  • 後置處理器那塊内容,我們先不研究,先走主線,看對屬性注入。【一般Spring不建議autowire的配置,是以不再看該源碼】

是以我們繼續看applyPropertyValues方法: 代碼1.3:AbstractAutowireCapableBeanFactory類的applyPropertyValues方法

protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {
		if (pvs == null || pvs.isEmpty()) {
			return;
		}

		MutablePropertyValues mpvs = null;//封裝屬性值
		List<PropertyValue> original;
		
		if (System.getSecurityManager()!= null) {
			if (bw instanceof BeanWrapperImpl) {
				//設定安全上下文,JDK安全機制  
				((BeanWrapperImpl) bw).setSecurityContext(getAccessControlContext());
			}
		}

		if (pvs instanceof MutablePropertyValues) {
			mpvs = (MutablePropertyValues) pvs;
			//屬性值已經轉換 
			if (mpvs.isConverted()) {
				try {
					//為執行個體化對象設定屬性值  
					bw.setPropertyValues(mpvs);
					return;
				}
				catch (BeansException ex) {
					throw new BeanCreationException(
							mbd.getResourceDescription(), beanName, "Error setting property values", ex);
				}
			}
			//擷取屬性值對象的原始類型值
			original = mpvs.getPropertyValueList();
		}
		else {
			original = Arrays.asList(pvs.getPropertyValues());
		}
		
		 //擷取使用者自定義的類型轉換 
		TypeConverter converter = getCustomTypeConverter();
		if (converter == null) {
			converter = bw;
		}
		 //建立一個Bean定義屬性值解析器,将Bean定義中的屬性值解析為Bean執行個體對象的實際值  
		BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, converter);

		//為屬性的解析值建立一個拷貝,将拷貝的資料注入到執行個體對象中 
		List<PropertyValue> deepCopy = new ArrayList<PropertyValue>(original.size());
		boolean resolveNecessary = false;
		for (PropertyValue pv : original) {
			//屬性值不需要轉換  
			if (pv.isConverted()) {
				deepCopy.add(pv);
			}
			else {//屬性值需要轉換 
				String propertyName = pv.getName();
				Object originalValue = pv.getValue();//原始值
				
				//轉換屬性值,例如将引用轉換為IoC容器中執行個體化對象引用
				Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue);
				
				Object convertedValue = resolvedValue;//轉換後的值
				//屬性值是否可以轉換  
				boolean convertible = bw.isWritableProperty(propertyName) &&
						!PropertyAccessorUtils.isNestedOrIndexedProperty(propertyName);
				if (convertible) {
					//如果還可以轉換,使用使用者自定義的類型轉換器轉換屬性值  
					convertedValue = convertForProperty(resolvedValue, propertyName, bw, converter);
				}
				
				//存儲轉換後的屬性值,避免每次屬性注入時的轉換工作 
				if (resolvedValue == originalValue) {
					if (convertible) {
						//設定屬性轉換之後的值  
						pv.setConvertedValue(convertedValue);
					}
					deepCopy.add(pv);
				}
				//屬性是可轉換的,且屬性原始值是字元串類型,且屬性的原始類型值不是動态生成的字元串,且屬性的原始值不是集合或者數組類型
				else if (convertible && originalValue instanceof TypedStringValue &&
						!((TypedStringValue) originalValue).isDynamic() &&
						!(convertedValue instanceof Collection || ObjectUtils.isArray(convertedValue))) {
					pv.setConvertedValue(convertedValue);
					deepCopy.add(pv);
				}
				else {
					resolveNecessary = true;
					deepCopy.add(new PropertyValue(pv, convertedValue));
				}
			}
		}
		if (mpvs != null && !resolveNecessary) {
			//标記屬性值已經轉換過 
			mpvs.setConverted();
		}

		//進行屬性依賴注入 
		try {
			bw.setPropertyValues(new MutablePropertyValues(deepCopy));
		}
		catch (BeansException ex) {
			throw new BeanCreationException(
					mbd.getResourceDescription(), beanName, "Error setting property values", ex);
		}
	}
           

我們簡單來看下這個代碼的執行順序:首先看屬性是否已經是符合注入标準的類型MutablePropertyValues,如果是就直接開始注入-->否則,判斷屬性是否需要轉換解析,需要的話則進行解析-->解析完成,開始注入。 這裡有一點要回憶一下,大家可記得我們在Beandefinition載入和解析的時候,對于Property元素及子元素做了一些操作,比如我們ref被解析成RuntimeBeanReference,list被解析成MangedList。那麼,我們當時說了,這麼做是為了把bean的配置解析成Spring能夠認識的内部結構,是以這些内部結構現在就要被我們用來依賴注入了,Spring就是從這些結構中完成對屬性的轉換。

是以我們有必要去看下Spring如何解析屬性值,來看代碼: 代碼1.4:BeanDefinitionValueResolver類的resolveValueIfNecessary方法:

public Object resolveValueIfNecessary(Object argName, Object value) {
		//對引用類型的屬性進行解析
		if (value instanceof RuntimeBeanReference) {
			RuntimeBeanReference ref = (RuntimeBeanReference) value;
			return resolveReference(argName, ref);
		}
		//對屬性值是引用容器中另一個Bean名稱的解析
		else if (value instanceof RuntimeBeanNameReference) {
			String refName = ((RuntimeBeanNameReference) value).getBeanName();
			refName = String.valueOf(evaluate(refName));
			if (!this.beanFactory.containsBean(refName)) {
				throw new BeanDefinitionStoreException(
						"Invalid bean name '" + refName + "' in bean reference for " + argName);
			}
			return refName;
		}
		//對Bean類型屬性的解析,主要是Bean中的内部類
		else if (value instanceof BeanDefinitionHolder) {
			// Resolve BeanDefinitionHolder: contains BeanDefinition with name and aliases.
			BeanDefinitionHolder bdHolder = (BeanDefinitionHolder) value;
			return resolveInnerBean(argName, bdHolder.getBeanName(), bdHolder.getBeanDefinition());
		}
		else if (value instanceof BeanDefinition) {
			// Resolve plain BeanDefinition, without contained name: use dummy name.
			BeanDefinition bd = (BeanDefinition) value;
			return resolveInnerBean(argName, "(inner bean)", bd);
		}
		//對集合數組類型的屬性解析  
		else if (value instanceof ManagedArray) {
			ManagedArray array = (ManagedArray) value;
			Class elementType = array.resolvedElementType;//擷取數組的類型  
			if (elementType == null) {
				String elementTypeName = array.getElementTypeName();//擷取數組元素的類型 
				if (StringUtils.hasText(elementTypeName)) {
					try {
						 //使用反射機制建立指定類型的對象  
						elementType = ClassUtils.forName(elementTypeName, this.beanFactory.getBeanClassLoader());
						array.resolvedElementType = elementType;
					}
					catch (Throwable ex) {
						throw new BeanCreationException(
								this.beanDefinition.getResourceDescription(), this.beanName,
								"Error resolving array type for " + argName, ex);
					}
				}
				else {
					//沒有擷取到數組的類型,也沒有擷取到數組元素的類型,則直接設定數組的類型為Object  
					elementType = Object.class;
				}
			}
			return resolveManagedArray(argName, (List<?>) value, elementType);
		}
		//解析list類型的屬性值
		else if (value instanceof ManagedList) {
			return resolveManagedList(argName, (List<?>) value);
		}
		 //解析set類型的屬性值
		else if (value instanceof ManagedSet) {
			return resolveManagedSet(argName, (Set<?>) value);
		}
		//解析map類型的屬性值
		else if (value instanceof ManagedMap) {
			return resolveManagedMap(argName, (Map<?, ?>) value);
		}
		//解析props類型的屬性值,props其實就是key和value均為字元串的map
		else if (value instanceof ManagedProperties) {
			Properties original = (Properties) value;
			Properties copy = new Properties();
			for (Map.Entry propEntry : original.entrySet()) {
				Object propKey = propEntry.getKey();
				Object propValue = propEntry.getValue();
				if (propKey instanceof TypedStringValue) {
					propKey = evaluate((TypedStringValue) propKey);
				}
				if (propValue instanceof TypedStringValue) {
					propValue = evaluate((TypedStringValue) propValue);
				}
				copy.put(propKey, propValue);
			}
			return copy;
		}
		//解析字元串類型的屬性值
		else if (value instanceof TypedStringValue) {
			// Convert value to target type here.
			TypedStringValue typedStringValue = (TypedStringValue) value;
			Object valueObject = evaluate(typedStringValue);
			try {
				Class<?> resolvedTargetType = resolveTargetType(typedStringValue);
				if (resolvedTargetType != null) {
					return this.typeConverter.convertIfNecessary(valueObject, resolvedTargetType);
				}
				else {
					return valueObject;
				}
			}
			catch (Throwable ex) {
				// Improve the message by showing the context.
				throw new BeanCreationException(
						this.beanDefinition.getResourceDescription(), this.beanName,
						"Error converting typed String value for " + argName, ex);
			}
		}
		else {
			return evaluate(value);
		}
	}
           

從上面的代碼我們可以看到, 這裡的轉換幾乎完全跟BeanDefinitionParserDelegate中的parserPropertySubElement方法中對應,那裡是為了将bean的配置解析成Spring内部結構,這裡由于我們bean已經建立完成,是以我們需要将具體的屬性值給指派上真正的内容(比如引用類型,這時候就要真正的給一個bean執行個體)。 我們可以看到,這裡是根據不同的屬性類型,分别進入了不同的方法,我們簡單舉幾個例子看下: 代碼1.5:BeanDefinitionValueResolver類的屬性解析舉例

private Object resolveReference(Object argName, RuntimeBeanReference ref) {  
        try {  
            //擷取引用的Bean名稱  
            String refName = ref.getBeanName();  
            refName = String.valueOf(evaluate(refName));  
            //如果引用的對象在父類容器中,則從父類容器中擷取指定的引用對象  
            if (ref.isToParent()) {  
                if (this.beanFactory.getParentBeanFactory() == null) {  
                    throw new BeanCreationException(  
                            this.beanDefinition.getResourceDescription(), this.beanName,  
                            "Can't resolve reference to bean '" + refName +  
                            "' in parent factory: no parent factory available");  
                }  
                return this.beanFactory.getParentBeanFactory().getBean(refName);  
            }  
            //從目前的容器中擷取指定的引用Bean對象,如果指定的Bean沒有被執行個體化則會遞歸觸發引用Bean的初始化和依賴注入  
            else {  
                Object bean = this.beanFactory.getBean(refName);  
                //将目前執行個體化對象的依賴引用對象  
                this.beanFactory.registerDependentBean(refName, this.beanName);  
                return bean;  
            }  
        }  
        catch (BeansException ex) {  
            throw new BeanCreationException(  
                    this.beanDefinition.getResourceDescription(), this.beanName,  
                    "Cannot resolve reference to bean '" + ref.getBeanName() + "' while setting " + argName, ex);  
        }  
    }   
	//解析array類型的屬性  
	private Object resolveManagedArray(Object argName, List<?> ml, Class elementType) {  
	        //建立一個指定類型的數組,用于存放和傳回解析後的數組  
	        Object resolved = Array.newInstance(elementType, ml.size());  
	        for (int i = 0; i < ml.size(); i++) {  
	        //遞歸解析array的每一個元素,并将解析後的值設定到resolved數組中,索引為i  
	            Array.set(resolved, i,  
	                resolveValueIfNecessary(new KeyedArgName(argName, i), ml.get(i)));  
	        }  
	        return resolved;  
	    }  
    //解析list類型的屬性  
    private List resolveManagedList(Object argName, List<?> ml) {  
        List<Object> resolved = new ArrayList<Object>(ml.size());  
        for (int i = 0; i < ml.size(); i++) {  
            //遞歸解析list的每一個元素  
            resolved.add(  
                resolveValueIfNecessary(new KeyedArgName(argName, i), ml.get(i)));  
        }  
        return resolved;  
    }  
    //解析set類型的屬性  
    private Set resolveManagedSet(Object argName, Set<?> ms) {  
        Set<Object> resolved = new LinkedHashSet<Object>(ms.size());  
        int i = 0;  
        //遞歸解析set的每一個元素  
        for (Object m : ms) {  
            resolved.add(resolveValueIfNecessary(new KeyedArgName(argName, i), m));  
            i++;  
        }  
        return resolved;  
    }  
    //解析map類型的屬性  
    private Map resolveManagedMap(Object argName, Map<?, ?> mm) {  
        Map<Object, Object> resolved = new LinkedHashMap<Object, Object>(mm.size());  
        //遞歸解析map中每一個元素的key和value  
        for (Map.Entry entry : mm.entrySet()) {  
            Object resolvedKey = resolveValueIfNecessary(argName, entry.getKey());  
            Object resolvedValue = resolveValueIfNecessary(  
                    new KeyedArgName(argName, entry.getKey()), entry.getValue());  
            resolved.put(resolvedKey, resolvedValue);  
        }  
        return resolved;  
    } 
           

上面的代碼我們可以從以下幾個點來了解:

  • 引用類型的解析:如果引用的對象在父類容器中,則從父類容器中擷取指定的引用對象 ,從目前容器取,如果對象沒有建立,則遞歸調用getBean。
  • 其他類型的解析:如list,遞歸解析list的每一個元素,又走了一遍resolveValueIfNecessary方法,也就是說如果list裡面也是配置的ref,那麼會遞歸調用到對引用類型解析。注意這裡的遞歸調用。

bean屬性的注入

OK,通過上面的源碼分析,我們已經得到了解析好的屬性值,也就是說這時候的屬性裡面就是具體的對象,String等内容了。是以這時候我們就可以對屬性進行注入了。在applyPropertyValues方法中,我們可以看到bw.setPropertyValues方法,我們看到的是BeanWrapper.setPropertyValues,但是當我們點進去确實來到了AbstractPropertyAccessor類的方法中,原因是: BeanWrapper繼承了PropertyAccessor接口,而AbstractPropertyAccessor實作了PropertyAccessor接口,這裡就是運用了組合複用的設計模式。我們先來跟一下這個方法,然後找到具體的實作類。 代碼1.6:AbstractPropertyAccessor類的setPropertyValues方法

//該方法--調用入口
	public void setPropertyValues(PropertyValues pvs) throws BeansException {
		setPropertyValues(pvs, false, false);
	}
	public void setPropertyValues(PropertyValues pvs, boolean ignoreUnknown, boolean ignoreInvalid)
			throws BeansException {

		List<PropertyAccessException> propertyAccessExceptions = null;
		//得到屬性清單
		List<PropertyValue> propertyValues = (pvs instanceof MutablePropertyValues ?
				((MutablePropertyValues) pvs).getPropertyValueList() : Arrays.asList(pvs.getPropertyValues()));
		for (PropertyValue pv : propertyValues) {
			try {
				//屬性注入
				setPropertyValue(pv);
			}
			catch (NotWritablePropertyException ex) {
				if (!ignoreUnknown) {
					throw ex;
				}
			}
			catch (NullValueInNestedPathException ex) {
				if (!ignoreInvalid) {
					throw ex;
				}
			}
			catch (PropertyAccessException ex) {
				if (propertyAccessExceptions == null) {
					propertyAccessExceptions = new LinkedList<PropertyAccessException>();
				}
				propertyAccessExceptions.add(ex);
			}
		}
		if (propertyAccessExceptions != null) {
			PropertyAccessException[] paeArray =
					propertyAccessExceptions.toArray(new PropertyAccessException[propertyAccessExceptions.size()]);
			throw new PropertyBatchUpdateException(paeArray);
		}
	}
           

上面代碼的作用就是得到屬性清單,并對每一個屬性進行注入,setPropertyValue的具體實作是在BeanWrapperImpl類中,這裡是有點煩。我們具體看該方法: 代碼1.7:BeanWrapperImpl類的setPropertyValue方法

public void setPropertyValue(PropertyValue pv) throws BeansException {
		PropertyTokenHolder tokens = (PropertyTokenHolder) pv.resolvedTokens;
		if (tokens == null) {//如果tokens為空
			String propertyName = pv.getName();
			BeanWrapperImpl nestedBw;
			try {
				nestedBw = getBeanWrapperForPropertyPath(propertyName);
			}
			catch (NotReadablePropertyException ex) {
				throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName,
						"Nested property in path '" + propertyName + "' does not exist", ex);
			}
			tokens = getPropertyNameTokens(getFinalPath(nestedBw, propertyName));
			if (nestedBw == this) {
				pv.getOriginalPropertyValue().resolvedTokens = tokens;
			}
			nestedBw.setPropertyValue(tokens, pv);
		}
		else {//不為空直接開始注入
			setPropertyValue(tokens, pv);
		}
	}
           

這個方法很關鍵,不過《Spring技術内幕》和網上的閑雜資料都沒有講解該方法的,我相信 90%以上的同學會看不懂這個方法。我在網上看了很多資料,大概知道幾個重要方法的作用,這裡簡單說下:

  • getBeanWrapperForPropertyPath:通過嵌套屬性的路徑遞歸得到一個BeanWrapperImpl執行個體
    protected BeanWrapperImpl getBeanWrapperForPropertyPath(String propertyPath) {
    		int pos = PropertyAccessorUtils.getFirstNestedPropertySeparatorIndex(propertyPath);
    		// Handle nested properties recursively.
    		if (pos > -1) {
    			String nestedProperty = propertyPath.substring(0, pos);
    			String nestedPath = propertyPath.substring(pos + 1);
    			BeanWrapperImpl nestedBw = getNestedBeanWrapper(nestedProperty);
    			return nestedBw.getBeanWrapperForPropertyPath(nestedPath);
    		}
    		else {
    			return this;
    		}
    	}
               
    這段代碼的作用就是:比如我們傳過來的propertyPath是beanA.beanB,那麼這裡得到的就是beanB的BeanWrapperImpl執行個體。
  • getPropertyNameTokens:解析指定的屬性名稱,并指派到對應的屬性标示中(PropertyTokenHolder)
    private PropertyTokenHolder getPropertyNameTokens(String propertyName) {
    		PropertyTokenHolder tokens = new PropertyTokenHolder();
    		String actualName = null;
    		List<String> keys = new ArrayList<String>(2);
    		int searchIndex = 0;
    		while (searchIndex != -1) {
    			int keyStart = propertyName.indexOf(PROPERTY_KEY_PREFIX, searchIndex);
    			searchIndex = -1;
    			if (keyStart != -1) {
    				int keyEnd = propertyName.indexOf(PROPERTY_KEY_SUFFIX, keyStart + PROPERTY_KEY_PREFIX.length());
    				if (keyEnd != -1) {
    					if (actualName == null) {
    						actualName = propertyName.substring(0, keyStart);
    					}
    					String key = propertyName.substring(keyStart + PROPERTY_KEY_PREFIX.length(), keyEnd);
    					if ((key.startsWith("'") && key.endsWith("'")) || (key.startsWith("\"") && key.endsWith("\""))) {
    						key = key.substring(1, key.length() - 1);
    					}
    					keys.add(key);
    					searchIndex = keyEnd + PROPERTY_KEY_SUFFIX.length();
    				}
    			}
    		}
    		tokens.actualName = (actualName != null ? actualName : propertyName);
    		tokens.canonicalName = tokens.actualName;
    		if (!keys.isEmpty()) {
    			tokens.canonicalName +=
    					PROPERTY_KEY_PREFIX +
    					StringUtils.collectionToDelimitedString(keys, PROPERTY_KEY_SUFFIX + PROPERTY_KEY_PREFIX) +
    					PROPERTY_KEY_SUFFIX;
    			tokens.keys = StringUtils.toStringArray(keys);
    		}
    		return tokens;
    	}
               
    這段代碼可以舉個例子:比如輸入 infoList[2],那麼tokens.actualName=infoList,tokens.canonicalName=infoList[2],tokens.keys=["2"];
  • 是以:我納悶的是,我們在對Property屬性注入的時候,哪來的這樣類型的資料。而且這個tokens是用來判斷屬性是集合類型還是其他類型的根據,真的想不通!希望得到大家的指點!           【add 20160805】--今天debug了一天,就是想找找怎樣配置才能弄出這樣的資料,後來發現我們項目中即使是如下的配置:
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        	<!--dataSource屬性指定要用到的資料源,是以在Hibernate的核心配置檔案中就無需再配置與資料庫連接配接相關的屬性-->
        	<property name="dataSource" ref="builderDataSource" />
        	
        	<property name="hibernateProperties">
    		<props>			
    			<!-- Hibernate基本配置 -->
    			<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
        			<prop key="hibernate.connection.pool_size">10</prop>
        			<prop key="hibernate.cache.provider_class">net.sf.ehcache.hibernate.EhCacheProvider</prop>
        			<prop key="hibernate.show_sql">true</prop>
        			<prop key="hibernate.format_sql">false</prop>
        			<prop key="hibernate.hbm2ddl.auto">update</prop>
        			
        			<!-- 結果集滾動 -->
        			<prop key="jdbc.use_scrollable_resultset">false</prop>
    		</props>
    	</property>
        	
        	<!-- 加入使用注解的實體類,用掃描的方式-->
    	<property name="packagesToScan">
    	     <list>
    	         <value>com.gh.codebuilder.entity.*</value>
    	     </list>
    	 </property>
        </bean>
               
    得到的tokens也是null,也就是說依然是用jdk反射調用setter方法處理的。是以這裡應該不是針對bean在配置的使用,有可能像我們在JSP送出form的時候 user.name,user.ids[0]之類的這個時候才用得到。【待驗證】

OK,言歸正傳,真正的屬性解析還在setPropertyValue方法中,我們先跳過這裡去看下源碼【該方法很長】: 代碼1.:8: BeanWrapperImpl類的 setPropertyValue方法:

@SuppressWarnings("unchecked")
	private void setPropertyValue(PropertyTokenHolder tokens, PropertyValue pv) throws BeansException {
		String propertyName = tokens.canonicalName;
		String actualName = tokens.actualName;
		 //keys是用來儲存集合類型屬性的size 
		if (tokens.keys != null) {
			//将屬性資訊拷貝  
			PropertyTokenHolder getterTokens = new PropertyTokenHolder();
			getterTokens.canonicalName = tokens.canonicalName;
			getterTokens.actualName = tokens.actualName;
			getterTokens.keys = new String[tokens.keys.length - 1];
			System.arraycopy(tokens.keys, 0, getterTokens.keys, 0, tokens.keys.length - 1);
			Object propValue;
			try {
				//擷取屬性值,該方法内部使用JDK的内省( Introspector)機制,調用屬性的getter(readerMethod)方法,擷取屬性的值  
				propValue = getPropertyValue(getterTokens);
			}
			catch (NotReadablePropertyException ex) {
				throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName,
						"Cannot access indexed value in property referenced " +
						"in indexed property path '" + propertyName + "'", ex);
			}
			//擷取集合類型屬性的長度
			String key = tokens.keys[tokens.keys.length - 1];
			if (propValue == null) {
				throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName,
						"Cannot access indexed value in property referenced " +
						"in indexed property path '" + propertyName + "': returned null");
			}
			//注入array類型的屬性值  
			else if (propValue.getClass().isArray()) {
				//擷取屬性的描述符 
				PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
				//擷取數組的類型 
				Class requiredType = propValue.getClass().getComponentType();
				//擷取數組的長度  
				int arrayIndex = Integer.parseInt(key);
				Object oldValue = null;
				try {
					 //擷取數組以前初始化的值
					if (isExtractOldValueForEditor()) {
						oldValue = Array.get(propValue, arrayIndex);
					}
					//将屬性的值指派給數組中的元素
					Object convertedValue = convertIfNecessary(propertyName, oldValue, pv.getValue(), requiredType,
							new PropertyTypeDescriptor(pd, new MethodParameter(pd.getReadMethod(), -1), requiredType));
					Array.set(propValue, arrayIndex, convertedValue);
				}
				catch (IndexOutOfBoundsException ex) {
					throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
							"Invalid array index in property path '" + propertyName + "'", ex);
				}
			}
			//注入list類型的屬性值
			else if (propValue instanceof List) {
				PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
				//擷取list集合的類型  
				Class requiredType = GenericCollectionTypeResolver.getCollectionReturnType(
						pd.getReadMethod(), tokens.keys.length);
				List list = (List) propValue;
				//擷取list集合的size  
				int index = Integer.parseInt(key);
				Object oldValue = null;
				if (isExtractOldValueForEditor() && index < list.size()) {
					oldValue = list.get(index);
				}
				//擷取list解析後的屬性值
				Object convertedValue = convertIfNecessary(propertyName, oldValue, pv.getValue(), requiredType,
						new PropertyTypeDescriptor(pd, new MethodParameter(pd.getReadMethod(), -1), requiredType));
				if (index < list.size()) {
					//為list屬性指派  
					list.set(index, convertedValue);
				}
				else if (index >= list.size()) {//如果list的長度大于屬性值的長度,則多餘的元素指派為null 
					for (int i = list.size(); i < index; i++) {
						try {
							list.add(null);
						}
						catch (NullPointerException ex) {
							throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
									"Cannot set element with index " + index + " in List of size " +
									list.size() + ", accessed using property path '" + propertyName +
									"': List does not support filling up gaps with null elements");
						}
					}
					list.add(convertedValue);
				}
			}
			//注入map類型的屬性值
			else if (propValue instanceof Map) {
				PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
				Class mapKeyType = GenericCollectionTypeResolver.getMapKeyReturnType(
						pd.getReadMethod(), tokens.keys.length);
				Class mapValueType = GenericCollectionTypeResolver.getMapValueReturnType(
						pd.getReadMethod(), tokens.keys.length);
				Map map = (Map) propValue;
				Object convertedMapKey = convertIfNecessary(null, null, key, mapKeyType,
						new PropertyTypeDescriptor(pd, new MethodParameter(pd.getReadMethod(), -1), mapKeyType));
				Object oldValue = null;
				if (isExtractOldValueForEditor()) {
					oldValue = map.get(convertedMapKey);
				}
				Object convertedMapValue = convertIfNecessary(
						propertyName, oldValue, pv.getValue(), mapValueType,
						new TypeDescriptor(new MethodParameter(pd.getReadMethod(), -1, tokens.keys.length + 1)));
				map.put(convertedMapKey, convertedMapValue);
			}
			else {
				throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
						"Property referenced in indexed property path '" + propertyName +
						"' is neither an array nor a List nor a Map; returned value was [" + pv.getValue() + "]");
			}
		}

		else {//對非集合類型的屬性注入  
			PropertyDescriptor pd = pv.resolvedDescriptor;
			if (pd == null || !pd.getWriteMethod().getDeclaringClass().isInstance(this.object)) {
				pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
				//無法擷取到屬性名或者屬性沒有提供setter(寫方法)方法
				if (pd == null || pd.getWriteMethod() == null) {
					 //如果屬性值是可選的,即不是必須的,則忽略該屬性值 
					if (pv.isOptional()) {
						logger.debug("Ignoring optional value for property '" + actualName +
								"' - property not found on bean class [" + getRootClass().getName() + "]");
						return;
					}
					else {//如果屬性值是必須的,則抛出無法給屬性指派,因為沒提供setter方法異常  
						PropertyMatches matches = PropertyMatches.forProperty(propertyName, getRootClass());
						throw new NotWritablePropertyException(
								getRootClass(), this.nestedPath + propertyName,
								matches.buildErrorMessage(), matches.getPossibleMatches());
					}
				}
				pv.getOriginalPropertyValue().resolvedDescriptor = pd;
			}

			Object oldValue = null;
			try {
				Object originalValue = pv.getValue();
				Object valueToApply = originalValue;
				if (!Boolean.FALSE.equals(pv.conversionNecessary)) {
					if (pv.isConverted()) {
						valueToApply = pv.getConvertedValue();
					}
					else {
						if (isExtractOldValueForEditor() && pd.getReadMethod() != null) {
							//擷取屬性的getter方法(讀方法),JDK内省機制 
							final Method readMethod = pd.getReadMethod();
							//如果屬性的getter方法不是public通路控制權限的,即通路控制權限比較嚴格,則使用JDK的反射機制強行通路非public的方法(暴力讀取屬性值) 
							if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers()) &&
									!readMethod.isAccessible()) {
								if (System.getSecurityManager()!= null) {
									//匿名内部類,根據權限修改屬性的讀取控制限制 
									AccessController.doPrivileged(new PrivilegedAction<Object>() {
										public Object run() {
											readMethod.setAccessible(true);
											return null;
										}
									});
								}
								else {
									readMethod.setAccessible(true);
								}
							}
							try {
								//調用讀取屬性值的方法,擷取屬性值 
								if (System.getSecurityManager() != null) {
									oldValue = AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
										public Object run() throws Exception {
											return readMethod.invoke(object);
										}
									}, acc);
								}
								else {
									oldValue = readMethod.invoke(object);
								}
							}
							catch (Exception ex) {
								if (ex instanceof PrivilegedActionException) {
									ex = ((PrivilegedActionException) ex).getException();
								}
								if (logger.isDebugEnabled()) {
									logger.debug("Could not read previous value of property '" +
											this.nestedPath + propertyName + "'", ex);
								}
							}
						}
						//設定屬性的注入值
						valueToApply = convertForProperty(propertyName, oldValue, originalValue, pd);
					}
					pv.getOriginalPropertyValue().conversionNecessary = (valueToApply != originalValue);
				}
				//根據JDK的内省機制,擷取屬性的setter(寫方法)方法
				final Method writeMethod = (pd instanceof GenericTypeAwarePropertyDescriptor ?
						((GenericTypeAwarePropertyDescriptor) pd).getWriteMethodForActualAccess() :
						pd.getWriteMethod());
				//如果屬性的setter方法是非public,即通路控制權限比較嚴格,則使用JDK的反射機制,強行設定setter方法可通路(暴力為屬性指派) 
				if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers()) && !writeMethod.isAccessible()) {
					if (System.getSecurityManager()!= null) {
						AccessController.doPrivileged(new PrivilegedAction<Object>() {
							public Object run() {
								writeMethod.setAccessible(true);
								return null;
							}
						});
					}
					else {
						writeMethod.setAccessible(true);
					}
				}
				final Object value = valueToApply;
				if (System.getSecurityManager() != null) {
					try {
						AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
							public Object run() throws Exception {
								writeMethod.invoke(object, value);
								return null;
							}
						}, acc);
					}
					catch (PrivilegedActionException ex) {
						throw ex.getException();
					}
				}
				else {
					writeMethod.invoke(this.object, value);
				}
			}
			catch (TypeMismatchException ex) {
				throw ex;
			}
			catch (InvocationTargetException ex) {
				PropertyChangeEvent propertyChangeEvent =
						new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName, oldValue, pv.getValue());
				if (ex.getTargetException() instanceof ClassCastException) {
					throw new TypeMismatchException(propertyChangeEvent, pd.getPropertyType(), ex.getTargetException());
				}
				else {
					throw new MethodInvocationException(propertyChangeEvent, ex.getTargetException());
				}
			}
			catch (Exception ex) {
				PropertyChangeEvent pce =
						new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName, oldValue, pv.getValue());
				throw new MethodInvocationException(pce, ex);
			}
		}
	}
           

關于這個方法,大家不要慌,我們從以下幾點來看:

  • 根據tokens是否為空分為:集合類型和非集合類型。
  • 集合類型的注入:一般都是這麼個規律:根據key先去getter舊值,再取得已經轉換好的真正的執行個體值,setter到指定的位置。也就是書上說的:将其屬性值解析為目标類型的集合後直接指派給屬性
  • 非集合類型:大量使用了JDK的反射和内省機制,通過屬性的getter方法(reader method)擷取指定屬性注入以前的值,同時調用屬性的setter方法(writer method)為屬性設定注入後的值。

到這裡依賴注入就完事了,跟其他部落客不一樣,看到這裡我相信大家都暈了吧。我在本篇部落格上也抛出了問題。後面我應該還會再來一篇文章進行補充的,主要針對上面那個問題和對代碼流程的總結。

繼續閱讀