【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)爲屬性設置注入後的值。
到這裏依賴注入就完事了,跟其他博主不一樣,看到這裏我相信大家都暈了吧。我在本篇博客上也拋出了問題。後面我應該還會再來一篇文章進行補充的,主要針對上面那個問題和對代碼流程的總結。




發佈了42 篇原創文章 · 獲贊 37 · 訪問量 26萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章