1. 程式人生 > >IOC依賴注入

IOC依賴注入

5.4、IOC容器的依賴注入

1、依賴注入發生的時間

當Spring IOC容器完成了Bean定義資源的定位、載入和解析註冊以後,IOC容器已經管理類Bean定義的相關資料,但是此時IOC容器還沒有對所管理的Bean進行依賴注入。依賴注入在以下兩種情況發生:

(1)使用者第一次通過getBean方法向IOC容器索要Bean時,IOC容器觸發依賴注入。

(2)當用戶在Bean定義資源中為<Bean>元素配置了lazy-init屬性,即讓容器在解析註冊Bean定義時進行預例項化,觸發依賴注入。

BeanFactory介面定義了Spring IOC容器的基本功能規範,是Spring IOC容器所應遵守的最底層和最基本的程式設計規範。BeanFactory介面中定義了幾個getBean方法,就是使用者向IOC容器索取管理的Bean的方法。我們通過分析其子類的具體實現,理解Spring IOC容器在使用者索取Bean時如何完成依賴注入。

在BeanFactory中我們看到getBean(String)函式,它的具體實現在AbstractBeanFactory中。

2、AbstractBeanFactory通過getBean向IOC容器獲取被管理的Bean:AbstractBeanFactory的getBean相關方法的原始碼如下。

	//獲取IOC容器中指定名稱的Bean 
	public Object getBean(String name) throws BeansException {
		//doGetBean才是真正向IoC容器獲取被管理Bean的過程
		return doGetBean(name, null, null, false);
	}

	//獲取IOC容器中指定名稱和型別的Bean
	public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
		//doGetBean才是真正向IoC容器獲取被管理Bean的過程
		return doGetBean(name, requiredType, null, false);
	}

	//獲取IOC容器中指定名稱和引數的Bean
	public Object getBean(String name, Object... args) throws BeansException {
		//doGetBean才是真正向IoC容器獲取被管理Bean的過程 
		return doGetBean(name, null, args, false);
	}


	//獲取IOC容器中指定名稱、型別和引數的Bean
	public <T> T getBean(String name, Class<T> requiredType, Object... args) throws BeansException {
		//doGetBean才是真正向IoC容器獲取被管理Bean的過程
		return doGetBean(name, requiredType, args, false);
	}


	//真正實現向IOC容器獲取Bean的功能,也是觸發依賴注入功能的地方
	@SuppressWarnings("unchecked")
	protected <T> T doGetBean(
			final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly)
			throws BeansException {

		//根據指定的名稱獲取被管理Bean的名稱,剝離指定名稱中對容器的相關依賴  
	    //如果指定的是別名,將別名轉換為規範的Bean名稱
		final String beanName = transformedBeanName(name);
		Object bean;

		// Eagerly check singleton cache for manually registered singletons.
		//先從快取中取是否已經有被建立過的單態型別的Bean
	    //對於單例模式的Bean整個IOC容器中只建立一次,不需要重複建立
		Object sharedInstance = getSingleton(beanName);
		 //IOC容器建立單例模式Bean例項物件
		if (sharedInstance != null && args == null) {
			if (logger.isDebugEnabled()) {
				//如果指定名稱的Bean在容器中已有單例模式的Bean被建立
	            //直接返回已經建立的Bean
				if (isSingletonCurrentlyInCreation(beanName)) {
					logger.debug("Returning eagerly cached instance of singleton bean '" + beanName +
							"' that is not fully initialized yet - a consequence of a circular reference");
				}
				else {
					logger.debug("Returning cached instance of singleton bean '" + beanName + "'");
				}
			}
		    //獲取給定Bean的例項物件,主要是完成FactoryBean的相關處理  
            //注意:BeanFactory是管理容器中Bean的工廠,而FactoryBean是  
            //建立建立物件的工廠Bean,兩者之間有區別
			bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
		}

		else {
			// Fail if we're already creating this bean instance:
			// We're assumably within a circular reference.
			//快取沒有正在建立的單例模式Bean  
	        //快取中已經有已經建立的原型模式Bean
	        //但是由於迴圈引用的問題導致實 例化物件失敗
			if (isPrototypeCurrentlyInCreation(beanName)) {
				throw new BeanCurrentlyInCreationException(beanName);
			}

			// Check if bean definition exists in this factory.
			//對IOC容器中是否存在指定名稱的BeanDefinition進行檢查,首先檢查是否  
	        //能在當前的BeanFactory中獲取的所需要的Bean,如果不能則委託當前容器  
	        //的父級容器去查詢,如果還是找不到則沿著容器的繼承體系向父級容器查詢
			BeanFactory parentBeanFactory = getParentBeanFactory();
			//當前容器的父級容器存在,且當前容器中不存在指定名稱的Bean
			if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
				// Not found -> check parent.
				//解析指定Bean名稱的原始名稱
				String nameToLookup = originalBeanName(name);
				if (args != null) {
					// Delegation to parent with explicit args.
					//委派父級容器根據指定名稱和顯式的引數查詢
					return (T) parentBeanFactory.getBean(nameToLookup, args);
				}
				else {
					// No args -> delegate to standard getBean method.
					//委派父級容器根據指定名稱和型別查詢
					return parentBeanFactory.getBean(nameToLookup, requiredType);
				}
			}

			//建立的Bean是否需要進行型別驗證,一般不需要
			if (!typeCheckOnly) {
				//向容器標記指定的Bean已經被建立
				markBeanAsCreated(beanName);
			}

			try {
				//根據指定Bean名稱獲取其父級的Bean定義
		        //主要解決Bean繼承時子類合併父類公共屬性問題 
				final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
				checkMergedBeanDefinition(mbd, beanName, args);

				// Guarantee initialization of beans that the current bean depends on.
				//獲取當前Bean所有依賴Bean的名稱
				String[] dependsOn = mbd.getDependsOn();
				//如果當前Bean有依賴Bean
				if (dependsOn != null) {
					for (String dependsOnBean : dependsOn) {
						//遞迴呼叫getBean方法,獲取當前Bean的依賴Bean
						getBean(dependsOnBean);
						//把被依賴Bean註冊給當前依賴的Bean
						registerDependentBean(dependsOnBean, beanName);
					}
				}

				// Create bean instance.
				//建立單例模式Bean的例項物件
				if (mbd.isSingleton()) {
					//這裡使用了一個匿名內部類,建立Bean例項物件,並且註冊給所依賴的物件
					sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
						public Object getObject() throws BeansException {
							try {
								//建立一個指定Bean例項物件,如果有父級繼承,則合併子類和父類的定義
								return createBean(beanName, mbd, args);
							}
							catch (BeansException ex) {
								// Explicitly remove instance from singleton cache: It might have been put there
								// eagerly by the creation process, to allow for circular reference resolution.
								// Also remove any beans that received a temporary reference to the bean.
								//顯式地從容器單例模式Bean快取中清除例項物件
								destroySingleton(beanName);
								throw ex;
							}
						}
					});
					//獲取給定Bean的例項物件
					bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
				}

				//IOC容器建立原型模式Bean例項物件
				else if (mbd.isPrototype()) {
					// It's a prototype -> create a new instance.
					//原型模式(Prototype)是每次都會建立一個新的物件
					Object prototypeInstance = null;
					try {
						//回撥beforePrototypeCreation方法,預設的功能是註冊當前建立的原型物件
						beforePrototypeCreation(beanName);
						//建立指定Bean物件例項
						prototypeInstance = createBean(beanName, mbd, args);
					}
					finally {
						//回撥afterPrototypeCreation方法,預設的功能告訴IOC容器指定Bean的原型物件不再建立了
						afterPrototypeCreation(beanName);
					}
					//獲取給定Bean的例項物件
					bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
				}

				//要建立的Bean既不是單例模式,也不是原型模式,則根據Bean定義資源中  
		        //配置的生命週期範圍,選擇例項化Bean的合適方法,這種在Web應用程式中  
		        //比較常用,如:request、session、application等生命週期 
				else {
					String scopeName = mbd.getScope();
					final Scope scope = this.scopes.get(scopeName);
					//Bean定義資源中沒有配置生命週期範圍,則Bean定義不合法
					if (scope == null) {
						throw new IllegalStateException("No Scope registered for scope '" + scopeName + "'");
					}
					try {
						//這裡又使用了一個匿名內部類,獲取一個指定生命週期範圍的例項
						Object scopedInstance = scope.get(beanName, new ObjectFactory<Object>() {
							public Object getObject() throws BeansException {
								beforePrototypeCreation(beanName);
								try {
									return createBean(beanName, mbd, args);
								}
								finally {
									afterPrototypeCreation(beanName);
								}
							}
						});
						//獲取給定Bean的例項物件
						bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
					}
					catch (IllegalStateException ex) {
						throw new BeanCreationException(beanName,
								"Scope '" + scopeName + "' is not active for the current thread; " +
								"consider defining a scoped proxy for this bean if you intend to refer to it from a singleton",
								ex);
					}
				}
			}
			catch (BeansException ex) {
				cleanupAfterBeanCreationFailure(beanName);
				throw ex;
			}
		}

		// Check if required type matches the type of the actual bean instance.
		//對建立的Bean例項物件進行型別檢查
		if (requiredType != null && bean != null && !requiredType.isAssignableFrom(bean.getClass())) {
			try {
				return getTypeConverter().convertIfNecessary(bean, requiredType);
			}
			catch (TypeMismatchException ex) {
				if (logger.isDebugEnabled()) {
					logger.debug("Failed to convert bean '" + name + "' to required type [" +
							ClassUtils.getQualifiedName(requiredType) + "]", ex);
				}
				throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
			}
		}
		return (T) bean;
	}

通過上面對向IOC容器獲取Bean方法的解析,我們可以看到在Spring中,如果Bean定義的單例模式(Singleton),則容器在建立之前先從快取中查詢,以確保整個容器中只存在一個例項物件。如果Bean定義的是原型模式(Prototype),則容器每次都會建立一個新的例項物件。除此之外,Bean定義還可以擴充套件為指定其生命週期範圍。

上面的原始碼只是定義了根據Bean定義的模式,採取的不同建立Bean例項物件的策略,具體的Bean例項物件的建立過程由實現了ObjectFactory介面的匿名內部類的createBean方法完成,Objectfactory使用委派模式,具體的Bean例項建立過程交由其實現類的AbstractAutowireCapableBeanFactory完成,我們繼續分析AbstractAutowireCapableBeanFactory的createBean方法的原始碼,理解其建立

Bean例項的具體實現過程。

3、AbstractAutowireCapableBeanFactory建立Bean例項物件:

AbstractAutowireCapableBeanFactory類實現了ObjectFactory介面,建立容器指定的Bean例項物件。同時還建立的Bean例項物件進行初始化處理。其建立Bean例項物件的方法原始碼如下:

    //建立Bean例項物件
	@Override
	protected Object createBean(final String beanName, final RootBeanDefinition mbd, final Object[] args)
			throws BeanCreationException {

		if (logger.isDebugEnabled()) {
			logger.debug("Creating instance of bean '" + beanName + "'");
		}
		// Make sure bean class is actually resolved at this point.
		//判斷需要建立的Bean是否可以例項化,即是否可以通過當前的類載入器載入
		resolveBeanClass(mbd, beanName);

		// Prepare method overrides.
		//校驗和準備Bean中的方法覆蓋
		try {
			mbd.prepareMethodOverrides();
		}
		catch (BeanDefinitionValidationException ex) {
			throw new BeanDefinitionStoreException(mbd.getResourceDescription(),
					beanName, "Validation of method overrides failed", ex);
		}

		try {
			// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
			//如果Bean配置了初始化前和初始化後的處理器,則試圖返回一個需要建立Bean的代理物件
			Object bean = resolveBeforeInstantiation(beanName, mbd);
			if (bean != null) {
				return bean;
			}
		}
		catch (Throwable ex) {
			throw new BeanCreationException(mbd.getResourceDescription(), beanName,
					"BeanPostProcessor before instantiation of bean failed", ex);
		}

		//建立Bean的入口
		Object beanInstance = doCreateBean(beanName, mbd, args);
		if (logger.isDebugEnabled()) {
			logger.debug("Finished creating instance of bean '" + beanName + "'");
		}
		return beanInstance;
	}

	//真正建立Bean的方法 
	protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) {
		// Instantiate the bean.
		//封裝被建立的Bean物件
		BeanWrapper instanceWrapper = null;
		if (mbd.isSingleton()) {//單例模式的Bean,先從容器中快取中獲取同名Bean
			instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
		}
		if (instanceWrapper == null) {
			//建立例項物件
			instanceWrapper = createBeanInstance(beanName, mbd, args);
		}
		final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null);
		//獲取例項化物件的型別
		Class<?> beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null);

		// Allow post-processors to modify the merged bean definition.
		//呼叫PostProcessor後置處理器
		synchronized (mbd.postProcessingLock) {
			if (!mbd.postProcessed) {
				applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
				mbd.postProcessed = true;
			}
		}

		// Eagerly cache singletons to be able to resolve circular references
		// even when triggered by lifecycle interfaces like BeanFactoryAware.
		//向容器中快取單例模式的Bean物件,以防迴圈引用
		boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
				isSingletonCurrentlyInCreation(beanName));
		if (earlySingletonExposure) {
			if (logger.isDebugEnabled()) {
				logger.debug("Eagerly caching bean '" + beanName +
						"' to allow for resolving potential circular references");
			}
			//這裡是一個匿名內部類,為了防止迴圈引用,儘早持有物件的引用
			addSingletonFactory(beanName, new ObjectFactory<Object>() {
				public Object getObject() throws BeansException {
					return getEarlyBeanReference(beanName, mbd, bean);
				}
			});
		}

		// Initialize the bean instance.
		//Bean物件的初始化,依賴注入在此觸發  
	    //這個exposedObject在初始化完成之後返回作為依賴注入完成後的Bean
		Object exposedObject = bean;
		try {
			//將Bean例項物件封裝,並且Bean定義中配置的屬性值賦值給例項物件
			populateBean(beanName, mbd, instanceWrapper);
			if (exposedObject != null) {
				//初始化Bean物件 
				//在對Bean例項物件生成和依賴注入完成以後,開始對Bean例項物件  
	            //進行初始化 ,為Bean例項物件應用BeanPostProcessor後置處理器
				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) {
			//獲取指定名稱的已註冊的單例模式Bean物件
			Object earlySingletonReference = getSingleton(beanName, false);
			if (earlySingletonReference != null) {
				//根據名稱獲取的已註冊的Bean和正在例項化的Bean是同一個
				if (exposedObject == bean) {
					//當前例項化的Bean初始化完成
					exposedObject = earlySingletonReference;
				}
				//當前Bean依賴其他Bean,並且當發生迴圈引用時不允許新建立例項物件
				else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
					String[] dependentBeans = getDependentBeans(beanName);
					Set<String> actualDependentBeans = new LinkedHashSet<String>(dependentBeans.length);
					//獲取當前Bean所依賴的其他Bean 
					for (String dependentBean : dependentBeans) {
						//對依賴Bean進行型別檢查
						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 " +
								"'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
					}
				}
			}
		}

		// Register bean as disposable.
		//註冊完成依賴注入的Bean
		try {
			registerDisposableBeanIfNecessary(beanName, bean, mbd);
		}
		catch (BeanDefinitionValidationException ex) {
			throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
		}

		//為應用返回所需要的例項物件
		return exposedObject;
	}

通過對方法原始碼的分析。我們看到具體的依賴注入實現在一下兩個方法中:

(1):createBeanInstance:生成Bean所包含的java物件例項。

(2):populateBean:對Bean屬性的依賴注入進行處理。

下面繼續分析這兩個方法的程式碼實現。

 

4、createBeanInstance方法建立Bean的java例項物件:.

在createBeanInstance方法中,根據指定的初始化策略。使用靜態工廠。工廠方法或者容器的自動裝配特性生成java例項物件,建立物件原始碼如下。

	//建立Bean的例項物件
	protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, Object[] args) {
		// Make sure bean class is actually resolved at this point.
		//檢查確認Bean是可例項化的
		Class<?> beanClass = resolveBeanClass(mbd, beanName);

		//使用工廠方法對Bean進行例項化
		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());
		}

		if (mbd.getFactoryMethodName() != null)  {
			//呼叫工廠方法例項化
			return instantiateUsingFactoryMethod(beanName, mbd, args);
		}

		// Shortcut when re-creating the same bean...
		//使用容器的自動裝配方法進行例項化
		boolean resolved = false;
		boolean autowireNecessary = false;
		if (args == null) {
			synchronized (mbd.constructorArgumentLock) {
				if (mbd.resolvedConstructorOrFactoryMethod != null) {
					resolved = true;
					autowireNecessary = mbd.constructorArgumentsResolved;
				}
			}
		}
		if (resolved) {
			if (autowireNecessary) {
				//配置了自動裝配屬性,使用容器的自動裝配例項化  
	            //容器的自動裝配是根據引數型別匹配Bean的構造方法
				return autowireConstructor(beanName, mbd, null, null);
			}
			else {
				//使用預設的無參構造方法例項化
				return instantiateBean(beanName, mbd);
			}
		}

		// Need to determine the constructor...
		//使用Bean的構造方法進行例項化
		Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
		if (ctors != null ||
				mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR ||
				mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args))  {
			//使用容器的自動裝配特性,呼叫匹配的構造方法例項化 
			return autowireConstructor(beanName, mbd, ctors, args);
		}

		// No special handling: simply use no-arg constructor.
		//使用預設的無參構造方法例項化
		return instantiateBean(beanName, mbd);
	}


	//使用預設的無參構造方法例項化Bean物件
	protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) {
		try {
			Object beanInstance;
			final BeanFactory parent = this;
			//獲取系統的安全管理介面,JDK標準的安全管理AP
			if (System.getSecurityManager() != null) {
				//這裡是一個匿名內建類,根據例項化策略建立例項物件
				beanInstance = AccessController.doPrivileged(new PrivilegedAction<Object>() {
					public Object run() {
						return getInstantiationStrategy().instantiate(mbd, beanName, parent);
					}
				}, getAccessControlContext());
			}
			else {
				//將例項化的物件封裝起來
				beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);
			}
			BeanWrapper bw = new BeanWrapperImpl(beanInstance);
			initBeanWrapper(bw);
			return bw;
		}
		catch (Throwable ex) {
			throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
		}
	}

經過對上面的程式碼分析,我們可以看出,對使用工廠方法和自動裝配特性的Bean的例項化相對比較清楚,呼叫相應的工廠方法或者引數匹配的構造方法即可完成例項化物件的工作,但是對於我們最常使用的預設無參構造方法就需要使用相應的初始化策略(jdk的反射機制或者CGLIB)進行初始化了,在方法getInstantiationStrategy().instantiate中就具體實現類使用初始策略例項化物件。

5、SimpleInstantiationStrategy類使用預設的無參構造方法建立Bean例項化物件。

在使用預設的無參構造方法建立Bean的例項化物件時,方法getInstantiationStrategy().instantiate呼叫了SimpleInstantiationStrategy類中的例項化Bean的方法,其原始碼如下。

	//使用初始化策略例項化Bean物件
	public Object instantiate(RootBeanDefinition beanDefinition, String beanName, BeanFactory owner) {
		// Don't override the class with CGLIB if no overrides.
		//如果Bean定義中沒有方法覆蓋,則就不需要CGLIB父類類的方法
		if (beanDefinition.getMethodOverrides().isEmpty()) {
			Constructor<?> constructorToUse;
			synchronized (beanDefinition.constructorArgumentLock) {
				//獲取物件的構造方法或工廠方法
				constructorToUse = (Constructor<?>) beanDefinition.resolvedConstructorOrFactoryMethod;
				
				//如果沒有構造方法且沒有工廠方法 
				if (constructorToUse == null) {
					//使用JDK的反射機制,判斷要例項化的Bean是否是介面
					final Class clazz = beanDefinition.getBeanClass();
					if (clazz.isInterface()) {
						throw new BeanInstantiationException(clazz, "Specified class is an interface");
					}
					try {
						if (System.getSecurityManager() != null) {
							//這裡是一個匿名內建類,使用反射機制獲取Bean的構造方法
							constructorToUse = AccessController.doPrivileged(new PrivilegedExceptionAction<Constructor>() {
								public Constructor run() throws Exception {
									return clazz.getDeclaredConstructor((Class[]) null);
								}
							});
						}
						else {
							constructorToUse =	clazz.getDeclaredConstructor((Class[]) null);
						}
						beanDefinition.resolvedConstructorOrFactoryMethod = constructorToUse;
					}
					catch (Exception ex) {
						throw new BeanInstantiationException(clazz, "No default constructor found", ex);
					}
				}
			}
			//使用BeanUtils例項化,通過反射機制呼叫”構造方法.newInstance(arg)”來進行例項化
			return BeanUtils.instantiateClass(constructorToUse);
		}
		else {
			// Must generate CGLIB subclass.
			//使用CGLIB來例項化物件
			return instantiateWithMethodInjection(beanDefinition, beanName, owner);
		}
	}

通過上面的程式碼分析,我們看到了如果Bean有方法被覆蓋了,則使用JDK的反射機制進行例項化。否則,使用CGLIB進行例項化。

instantiateWithMethodInjection方法呼叫SimpleInstantiationStrategy的子類CgLibSubclassingInstantiationStrategy使用CGLIB來進行初始化其原始碼如下:

		//使用CGLIB進行Bean物件例項化
		public Object instantiate(Constructor ctor, Object[] args) {
			//CGLIB中的類
			Enhancer enhancer = new Enhancer();
			//將Bean本身作為其基類
			enhancer.setSuperclass(this.beanDefinition.getBeanClass());
			enhancer.setCallbackFilter(new CallbackFilterImpl());
			enhancer.setCallbacks(new Callback[] {
					NoOp.INSTANCE,
					new LookupOverrideMethodInterceptor(),
					new ReplaceOverrideMethodInterceptor()
			});

			//使用CGLIB的create方法生成例項物件
			return (ctor == null) ?
					enhancer.create() :
					enhancer.create(ctor.getParameterTypes(), args);
		}

CGLIB是一個常用的位元組碼生成器的類庫,他提供了一系列API實現java位元組碼的生成和轉換功能。我們在學習JDK的動態代理時都知道,JDK的動態代理只能針對介面,如果一個類沒有實現任何介面,要對其進行動態代理只能使用CGLIB。

6、populateBean方法對Bean屬性的依賴注入:

在第三部的分析中,我們已經瞭解到Bean的依賴注入分為以下兩個過程:

1).createBeanInstance:生成Bean所包含的java物件例項。

2).populateBean:對Bean屬性的依賴注入進行處理。

第4、5步中我們已經分析了容器初始化生成並所包含的Java例項物件的過程。現在我們繼續分析生成物件後,Spring IOC容器是如何將Bean的屬性依賴關係注入Bean例項物件中並設定好的,屬性依賴注入的程式碼如下:

	//將Bean屬性設定到生成的例項物件上
	protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) {
		//獲取容器在解析Bean定義資源時為BeanDefiniton中設定的屬性值
		PropertyValues pvs = mbd.getPropertyValues();

		//例項物件為null
		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.
				//例項物件為null,屬性值也為空,不需要設定屬性值,直接返回 
				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.
		//在設定屬性之前呼叫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);

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

			// Add property values based on autowire by type if applicable.
			//根據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, mbd.allowCaching);
			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);
	}

	//解析並注入依賴屬性的過程
	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()) {
				// Shortcut: use the pre-converted values as-is.
				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);

		// Create a deep copy, resolving any references for values.
		//為屬性的解析值建立一個拷貝,將拷貝的資料注入到例項物件中
		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);
				}
				// Possibly store converted value in merged bean definition,
				// in order to avoid re-conversion for every created bean instance.
				//儲存轉換後的屬性值,避免每次屬性注入時的轉換工作
				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();
		}

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

分析上述程式碼,我們可以看出,對屬性的注入過程分一下兩種情況:

1).屬性值型別不需要轉換時,不需要解析屬性值,直接準備進行依賴注入

2).屬性值需要進行型別轉換時,如對其他物件的引用等,首先需要解析屬性值,然後對解析後的屬性值進行依賴注入

對屬性值得解析是在BeanDefinitionValueResolver類中的resolveValueIfNecessary方法中進行的,對屬性值的依賴注入時通過bw.setPropertyValue方法實現的,在分析屬性值的依賴注入之前,我們首先分析一下對屬性值的解析過程。

7、BeanDefinitionValueResolver解析屬性值:

當容器在對屬性進行依賴注入時,如果發現屬性值需要進行型別轉換,如屬性值是容器中另一個Bean例項物件的引用,則容器首先需要根據屬性值解析出所引用的物件,然後才能將該引用物件注入到目標例項物件的屬性上去,對屬性進行解析的有resolveValueIfNecessary方法實現,其原始碼如下:

	//解析屬性值,對注入型別進行轉換
	public Object resolveValueIfNecessary(Object argName, Object value) {
		// We must check each value to see whether it requires a runtime reference
		// to another bean to be resolved.
		//對引用型別的屬性進行解析
		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));
			//從容器中獲取指定名稱的Bean
			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) {
			// May need to resolve contained runtime references.
			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) {
						// Improve the message by showing the context.
						throw new BeanCreationException(
								this.beanDefinition.getResourceDescription(), this.beanName,
								"Error resolving array type for " + argName, ex);
					}
				}
				//沒有獲取到陣列的型別,也沒有獲取到陣列元素的型別 
	            //則直接設定陣列的型別為Object
				else {
					elementType = Object.class;
				}
			}
			//建立指定型別的陣列
			return resolveManagedArray(argName, (List<?>) value, elementType);
		}
		//解析list型別的屬性值
		else if (value instanceof ManagedList) {
			// May need to resolve contained runtime references.
			return resolveManagedList(argName, (List<?>) value);
		}
		//解析set型別的屬性值
		else if (value instanceof ManagedSet) {
			// May need to resolve contained runtime references.
			return resolveManagedSet(argName, (Set<?>) value);
		}
		//解析map型別的屬性值
		else if (value instanceof ManagedMap) {
			// May need to resolve contained runtime references.
			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);
				}
				//沒有獲取到屬性的目標物件,則按Object型別返回
				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);
		}
	}

	//解析引用型別的屬性值
	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;
	}

通過上面的程式碼分析,我們明白了Spring是如何將引用型別,內部類以及集合型別等屬性進行解析的。屬性值解析完成後就可以進行依賴注入了,依賴注入的過程就是Bean物件例項設定到它所依賴的Bean物件屬性上去,在第七步中我們已經說過,依賴注入時通過bw.setPropertyValue方法實現的,該方法也是用了委託模式,在BeanWrapper介面中至少定義了方法宣告,依賴注入的具體實現交由其實現類BeanWrapperImpl來完成,下面我們就分析BeanWrapperImpl中依賴注入相關的原始碼。

8、BeanWrapperImpl對Bean屬性的依賴注入:

BeanWrapperImpl類主要是對容器中完成初始化的Bean市裡物件進行屬性的依賴注入,即吧Bean物件設定到它所依賴的另一個Bean的屬性中去,依賴注入的相關原始碼如下:

	//實現屬性依賴注入功能
	@SuppressWarnings("unchecked")
	private void setPropertyValue(PropertyTokenHolder tokens, PropertyValue pv) throws BeansException {
		//PropertyTokenHolder主要儲存屬性的名稱、路徑,以及集合的size等資訊
		String propertyName = tokens.canonicalName;
		String actualName = tokens.actualName;

		//keys是用來儲存集合型別屬性的size
		if (tokens.keys != null) {
			// Apply indexes and map keys: fetch value for all keys but the last one.
			//將屬性資訊拷貝
			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);
			}
			// Set value for last key.
			//獲取集合型別屬性的長度
			String key = tokens.keys[tokens.keys.length - 1];
			if (propValue == null) {
				// null map value case
				if (this.autoGrowNestedPaths) {
					// TODO: cleanup, this is pretty hacky
					int lastKeyIndex = tokens.canonicalName.lastIndexOf('[');
					getterTokens.canonicalName = tokens.canonicalName.substring(0, lastKeyIndex);
					propValue = setDefaultValue(getterTokens);
				}
				else {
					throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName,
							"Cannot access indexed value in property referenced " +
							"in indexed property path '" + propertyName + "': returned null");
				}
			}
			//注入array型別的屬性值
			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() && arrayIndex < Array.getLength(propValue)) {
						oldValue = Array.get(propValue, arrayIndex);
					}
					//將屬性的值賦值給陣列中的元素
					Object convertedValue = convertIfNecessary(propertyName, oldValue, pv.getValue(),
							requiredType, TypeDescriptor.nested(property(pd), tokens.keys.length));
					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;
				
				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, TypeDescriptor.nested(property(pd), tokens.keys.length));
				//獲取list集合的size
				int size = list.size();
				//如果list的長度大於屬性值的長度,則多餘的元素賦值為null 
				if (index >= size && index < this.autoGrowCollectionLimit) {
					for (int i = 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 " +
									size + ", accessed using property path '" + propertyName +
									"': List does not support filling up gaps with null elements");
						}
					}
					list.add(convertedValue);
				}
				else {
					try {
						//為list屬性賦值
						list.set(index, convertedValue);
					}
					catch (IndexOutOfBoundsException ex) {
						throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
								"Invalid list index in property path '" + propertyName + "'", ex);
					}
				}
			}
			//注入map型別的屬性值
			else if (propValue instanceof Map) {
				PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
				//獲取map集合key的型別
				Class mapKeyType = GenericCollectionTypeResolver.getMapKeyReturnType(
						pd.getReadMethod(), tokens.keys.length);
				//獲取map集合value的型別
				Class mapValueType = GenericCollectionTypeResolver.getMapValueReturnType(
						pd.getReadMethod(), tokens.keys.length);
				Map map = (Map) propValue;
				// IMPORTANT: Do not pass full property name in here - property editors
				// must not kick in for map keys but rather only for map values.
				TypeDescriptor typeDescriptor = (mapKeyType != null ?
						TypeDescriptor.valueOf(mapKeyType) : TypeDescriptor.valueOf(Object.class));
				//解析map型別屬性key值
				Object convertedMapKey = convertIfNecessary(null, null, key, mapKeyType, typeDescriptor);
				Object oldValue = null;
				if (isExtractOldValueForEditor()) {
					oldValue = map.get(convertedMapKey);
				}
				// Pass full property name and old value in here, since we want full
				// conversion ability for map values.
				//解析map型別屬性value值
				Object convertedMapValue = convertIfNecessary(propertyName, oldValue, pv.getValue(),
						mapValueType, TypeDescriptor.nested(property(pd), tokens.keys.length));
				//將解析後的key和value值賦值給map集合屬性
				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;
					}
					//如果屬性值是必須的,則丟擲無法給屬性賦值,因為沒提供setter方法異常
					else {
						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 {
								 //屬性沒有提供getter方法時,呼叫潛在的讀取屬性值的方法,獲取屬性值 
								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;
				 //如果使用了JDK的安全機制,則需要許可權驗證 
				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);
			}
		}
	}

通過對上面注入依賴程式碼的分析,我們已經明白了Spring IOC容器時如何將屬性的值注入到Bean例項物件中去的:

1). 對於集合型別的屬性,將其屬性值解析為目標型別的集合後直接賦值給屬性

2). 對於飛機盒型別的屬性,大量使用了jdk的反射和內省機制,通過屬性的getter方法(reader method)獲取制定屬性注入以前的值,同時呼叫屬性的setter方法(wirter method)為屬性設定注入後的值。看到這裡相信很多人都明白了spring 的Setter注入原理。

至此Spring IOC容器對Bean定義資原始檔的定位,載入、解析和依賴注入已經全部分析完畢,現在Spring IOC容器中管理了一系列靠依賴關係聯絡起來的Bean,程式不需要應用自己手動建立所需的物件,Spring IOC容器會在我們使用的時候自動為我們建立,並且為我們注入好相關的依賴,這就是Spring核心功能的控制反轉和依賴注入的相關功能。