您好,登錄后才能下訂單哦!
小編給大家分享一下Spring IoC容器中依賴注入原理的示例分析,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
具體如下:
IoC容器初始化的過程,主要完成的工作是在IoC容器中建立 BeanDefinition 數據映射,并沒有看到IoC容器對Bean依賴關系進行注入,
假設當前IoC容器已經載入用戶定義的Bean信息,依賴注入主要發生在兩個階段
正常情況下,由用戶第一次向IoC容器索要Bean時觸發
但我們可以在 BeanDefinition 信息中通過控制 lazy-init 屬性來讓容器完成對Bean的預實例化,即在初始化的過程中就完成某些Bean的依賴注入的過程
1.getBean觸發的依賴注入
在基本的IoC容器接口 BeanFactory 中,有一個 getBean 的接口定義,這個接口的實現就是觸發依賴注入發生的地方.為了進一步了解這個依賴注入的過程,我們從 DefaultListableBeanFactory 的基類 AbstractBeanFactory 入手去看看getBean的實現
// 這里是對 BeanFactory 接口的實現,比如getBean接口方法 //這些getBean接口方法最終是通過調用doGetBean來實現的 @Override public Object getBean(String name) throws BeansException { return doGetBean(name, null, null, false); } @Override public <T> T getBean(String name, Class<T> requiredType) throws BeansException { return doGetBean(name, requiredType, null, false); } @Override public Object getBean(String name, Object... args) throws BeansException { return doGetBean(name, null, args, false); } public <T> T getBean(String name, Class<T> requiredType, Object... args) throws BeansException { return doGetBean(name, requiredType, args, false); } //這里是實際取得Bean的地方,也就是觸發依賴注入發生的地方 @SuppressWarnings("unchecked") protected <T> T doGetBean( final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly) throws BeansException { final String beanName = transformedBeanName(name); Object bean; // Eagerly check singleton cache for manually registered singletons. //急切地檢查單例人士緩存手動注冊的單例 //先從緩存中取得Bean,處理那些已經被創建過的單例Bean,這種Bean不要重復創建 Object sharedInstance = getSingleton(beanName); if (sharedInstance != null && args == null) { if (logger.isDebugEnabled()) { 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 + "'"); } } //這里的getObjectForBeanInstance完成的是FactoryBean的相關處理,以取得FactoryBean的相關處理,以取得FactoryBean的生產結果,BeanFactory和FactoryBean的區別已在前面講過,這個過程在后面還會詳細地分析 bean = getObjectForBeanInstance(sharedInstance, name, beanName, null); } else { // Fail if we're already creating this bean instance: // We're assumably within a circular reference. if (isPrototypeCurrentlyInCreation(beanName)) { throw new BeanCurrentlyInCreationException(beanName); } // // 檢查IoC容器中的BeanDefinition是否存在,若在當前工廠不存在則去順著雙親BeanFactory鏈一直向上找 BeanFactory parentBeanFactory = getParentBeanFactory(); if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { // Not found -> check parent. 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); } } if (!typeCheckOnly) { markBeanAsCreated(beanName); } try { //根據Bean的名字取得BeanDefinition 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(); if (dependsOn != null) { for (String dep : dependsOn) { if (isDependent(beanName, dep)) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'"); } registerDependentBean(dep, beanName); getBean(dep); } } //通過調用createBean方法創建Singleton bean實例 if (mbd.isSingleton()) { sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() { @Override public Object getObject() throws BeansException { try { 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. destroySingleton(beanName); throw ex; } } }); bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd); } //這里是創建prototype bean的地方 else if (mbd.isPrototype()) { // It's a prototype -> create a new instance. Object prototypeInstance = null; try { beforePrototypeCreation(beanName); prototypeInstance = createBean(beanName, mbd, args); } finally { afterPrototypeCreation(beanName); } bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd); } else { String scopeName = mbd.getScope(); final Scope scope = this.scopes.get(scopeName); if (scope == null) { throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'"); } try { Object scopedInstance = scope.get(beanName, new ObjectFactory<Object>() { @Override public Object getObject() throws BeansException { beforePrototypeCreation(beanName); try { return createBean(beanName, mbd, args); } finally { afterPrototypeCreation(beanName); } } }); 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進行類型檢查,如果沒有問題,就返回這個新創建的Bean,這個Bean已經是包含了依賴關系的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; }
依賴注入就是在這里被觸發的.而依賴注入的發生是在容器中的BeanDefinition數據已經建立好的前提下進行的.雖然我們可以用最簡單的方式來描述IoC容器,那就是視其為一個HashMap,但只能說這個HashMap是容器的最基本的數據結構,而不是IoC容器的全部.
關于這個依賴注入過程會在下面詳解,圖1.1可以看到依賴注入的大致過程.
圖1.1 依賴注入的過程
getBean是依賴注入的起點,之后會調用AbstractAutowireCapableBeanFactory中的createBean來生產需要的Bean,還對Bean初始化進行了處理,比如實現了在BeanDefinition中的init-method屬性定義,Bean后置處理器等.下面通過createBean代碼了解這個過程
@Override protected Object createBean(String beanName, RootBeanDefinition mbd, Object[] args) throws BeanCreationException { if (logger.isDebugEnabled()) { logger.debug("Creating instance of bean '" + beanName + "'"); } RootBeanDefinition mbdToUse = mbd; // Make sure bean class is actually resolved at this point, and // clone the bean definition in case of a dynamically resolved Class // which cannot be stored in the shared merged bean definition. //這里判斷需要創建的Bean是否可以被實例化,這個類是否可以通過類加載器來載入 Class<?> resolvedClass = resolveBeanClass(mbd, beanName); if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) { mbdToUse = new RootBeanDefinition(mbd); mbdToUse.setBeanClass(resolvedClass); } // Prepare method overrides. try { mbdToUse.prepareMethodOverrides(); } catch (BeanDefinitionValidationException ex) { throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(), beanName, "Validation of method overrides failed", ex); } try { // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance. //如果Bean配置了PostProcessor,那么這里返回的是一個Proxy Object bean = resolveBeforeInstantiation(beanName, mbdToUse); if (bean != null) { return bean; } } catch (Throwable ex) { throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName, "BeanPostProcessor before instantiation of bean failed", ex); } try { Object beanInstance = doCreateBean(beanName, mbdToUse, args); if (logger.isDebugEnabled()) { logger.debug("Finished creating instance of bean '" + beanName + "'"); } return beanInstance; } catch (BeanCreationException ex) { // A previously detected exception with proper bean creation context already... throw ex; } catch (ImplicitlyAppearedSingletonException ex) { // An IllegalStateException to be communicated up to DefaultSingletonBeanRegistry... throw ex; } catch (Throwable ex) { throw new BeanCreationException( mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex); } } //接著到doCreate中去看看Bean是怎樣生成的 protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) { // Instantiate the bean. //用來持有創建出來的Bean對象 BeanWrapper instanceWrapper = null; //如果是單例,則先把緩存中的同名Bean清除 if (mbd.isSingleton()) { instanceWrapper = this.factoryBeanInstanceCache.remove(beanName); } //這里是創建Bean的地方,由createBeanInstance來完成 if (instanceWrapper == null) { //根據指定bean使用對應的策略創建新的實例,如:工廠方法,構造函數自動注入,簡單初始化 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. 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"); } //為避免后期循環依賴,可以在bean初始化完成前將創建實例的ObjectFactory加入工廠 addSingletonFactory(beanName, new ObjectFactory<Object>() { @Override public Object getObject() throws BeansException { //對bean再次依賴引用,主要應用SMartInstantialiationAware BeanPostProcessor, //其中我們熟知的AOP就是在這里將advice動態織入bean中,若無則直接返回bean,不做任何處理 return getEarlyBeanReference(beanName, mbd, bean); } }); } // Initialize the bean instance. //這里是對Bean的初始化,依賴注入往往在這里發生,這個exposedObject在初始化處理完后悔返回作為依賴注入完成后的Bean Object exposedObject = bean; try { //對bean進行填充,將各個屬性值注入,其中可能存在依賴于其他bean的屬性,則會遞歸初始化依賴bean populateBean(beanName, mbd, instanceWrapper); if (exposedObject != null) { //調用初始化方法,比如init-method exposedObject = initializeBean(beanName, exposedObject, mbd); } } catch (Throwable ex) { if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) { throw (BeanCreationException) ex; } else { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex); } } if (earlySingletonExposure) { Object earlySingletonReference = getSingleton(beanName, false); // earlySingletonReference 只有在檢測到有循環依賴的情況下才會非空 if (earlySingletonReference != null) { if (exposedObject == bean) { //如果exposedObject 沒有在初始化方法中被改變,也就是沒有被增強 exposedObject = earlySingletonReference; } else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) { String[] dependentBeans = getDependentBeans(beanName); Set<String> actualDependentBeans = new LinkedHashSet<String>(dependentBeans.length); for (String dependentBean : dependentBeans) { //檢測依賴 if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) { actualDependentBeans.add(dependentBean); } } //因為bean創建后其所依賴的bean一定是已經創建的,actualDependentBeans非空則表示當前bean創建后其依賴的bean卻沒有全部創建完,也就是說存在循環依賴 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. try { //根據scope注冊bean registerDisposableBeanIfNecessary(beanName, bean, mbd); } catch (BeanDefinitionValidationException ex) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex); } return exposedObject; }
依賴注入其實包括兩個主要過程
生產Bea所包含的Java對象
Bean對象生成之后,把這些Bean對象的依賴關系設置好
我們從上可以看到與依賴注入關系特別密切的方法有
createBeanInstance
生成Bean包含的Java對象
populateBean.
處理對各種Bean對象的屬性進行處理的過程(即依賴關系處理的過程)
先來看 createBeanInstance源碼
/** * Create a new instance for the specified bean, using an appropriate instantiation strategy: * factory method, constructor autowiring, or simple instantiation. * @param beanName the name of the bean * @param mbd the bean definition for the bean * @param args explicit arguments to use for constructor or factory method invocation * @return a BeanWrapper for the new instance */ 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); 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()); } Supplier<?> instanceSupplier = mbd.getInstanceSupplier(); if (instanceSupplier != null) { return obtainFromSupplier(instanceSupplier, beanName); } //若工廠方法非空,則使用工廠方法策略對Bean進行實例化 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) { //構造函數自動注入 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. //使用默認的構造函數對Bean進行實例化 return instantiateBean(beanName, mbd); } /** * Instantiate the given bean using its default constructor. * @param beanName the name of the bean * @param mbd the bean definition for the bean * @return a BeanWrapper for the new instance */ //最常見的實例化過程instantiateBean protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) { //使用默認的實例化策略對Bean進行實例化,默認的實例化策略是 //CglibSubclassingInstantiationStrategy,也就是使用CGLIB實例化Bean try { Object beanInstance; final BeanFactory parent = this; if (System.getSecurityManager() != null) { beanInstance = AccessController.doPrivileged(new PrivilegedAction<Object>() { @Override 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); } }
這里使用了CGLIB對Bean進行實例化.CGLIB是一個字節碼生成器的類庫,它提供了一系列的API來提供生成和轉換Java的字節碼的功能.
在Spring AOP中也使用CGLIB對Java的字節碼進行增強.在IoC容器中,要了解怎樣使用CGLIB來生成Bean對象,需要看一下SimpleInstantiationStrategy類.它是Spring用來生成Bean對象的默認類,它提供了兩種實例化Bean對象的方法
通過BeanUtils,使用了Java的反射功能
通過CGLIB來生成
public class SimpleInstantiationStrategy implements InstantiationStrategy { @Override public Object instantiate(RootBeanDefinition bd, String beanName, BeanFactory owner) { // Don't override the class with CGLIB if no overrides. if (bd.getMethodOverrides().isEmpty()) { //這里取得指定的構造器或者生成對象的工廠方法來對Bean進行實例化 Constructor<?> constructorToUse; synchronized (bd.constructorArgumentLock) { constructorToUse = (Constructor<?>) bd.resolvedConstructorOrFactoryMethod; if (constructorToUse == null) { final Class<?> clazz = bd.getBeanClass(); if (clazz.isInterface()) { throw new BeanInstantiationException(clazz, "Specified class is an interface"); } try { if (System.getSecurityManager() != null) { constructorToUse = AccessController.doPrivileged(new PrivilegedExceptionAction<Constructor<?>>() { @Override public Constructor<?> run() throws Exception { return clazz.getDeclaredConstructor((Class[]) null); } }); } else { constructorToUse = clazz.getDeclaredConstructor((Class[]) null); } bd.resolvedConstructorOrFactoryMethod = constructorToUse; } catch (Throwable ex) { throw new BeanInstantiationException(clazz, "No default constructor found", ex); } } } //通過BeanUtils進行實例化,這個BeanUtils的實例化通過Constructor來實例化Bean,在BeanUtils中可以看到具體的調用ctor.newInstance(args) return BeanUtils.instantiateClass(constructorToUse); } else { // 使用CGLIB來實例化對象 return instantiateWithMethodInjection(bd, beanName, owner); } } }
Bean之間依賴關系的處理
依賴關系處理的入口是前面提到的populateBean方法.由于其中涉及的面太多,在這里就不貼代碼了.簡要介紹一下依賴關系處理的流程:在populateBean方法中,
首先取得在BeanDefinition中設置的property值,然后開始依賴注入的過程。
首先處理autowire的注入,可以byName或者是byType,之后對屬性進行注入。
接著需要對Bean Reference進行解析,在對ManageList、ManageSet、ManageMap等進行解析完之后,就已經為依賴注入準備好了條件,這是真正把Bean對象設置到它所依賴的另一個Bean屬性中去的地方,其中處理的屬性是各種各樣的。
依賴注入發生在BeanWrapper的setPropertyValues中,具體的完成卻是在BeanWrapper的子類BeanWrapperImpl中實現的,它會完成Bean的屬性值的注入,其中包括對Array的注入、對List等集合類以及對非集合類的域進行注入。
進過一系列的注入,這樣就完成了對各種Bean屬性的依賴注入過程。
在Bean的創建和對象依賴注入的過程中,需要依據BeanDefinition中的信息來遞歸地完成依賴注入。
從前面的幾個遞歸過程中可以看到,這些遞歸都是以getBean為入口的。
一個遞歸是在上下文體系中查找需要的Bean和創建Bean的遞歸調用;
另一個遞歸是在依賴注入時,通過遞歸調用容器的getBean方法,得到當前Bean的依賴Bean,同時也觸發對依賴Bean的創建和注入。
在對Bean的屬性進行依賴注入時,解析的過程也是一個遞歸的過程。這樣,根據依賴關系,一層層地完成Bean的創建和注入,直到最后完成當前Bean的創建。有了這個頂層Bean的創建和對它屬性依賴注入的完成,意味著和當前Bean相關的整個依賴鏈的注入液完成了。
在Bean創建和依賴注入完成以后,在IoC容器中建立起一系列依靠依賴關系聯系起來的Bean,這個Bean已經不再是簡單的Java對象了。該Bean系列以及Bean之間的依賴關系建立完成之后,通過IoC的相關接口方法,就可以非常方便地供上層應用使用了。
2. lazy-init屬性和預實例化
在前面的refresh方法中,我們可以看到調用了finishBeanFactoryInitialization來對配置了lazy-init的Bean進行處理。
其實在這個方法中,封裝了對lazy-init屬性的處理,實際的處理是在DefaultListableBeanFactory這個基本容器的preInstantiateSingleton方法中完成的。該方法對單例Bean完成預實例化,這個預實例化的完成巧妙地委托給容器來實現。如果需要預實例化,那么就直接在這里采用getBean去觸發依賴注入,與正常依賴注入的觸發相比,只有觸發的時間和場合不同。在這里,依賴注入發生在容器執行refresh的過程中,即IoC容器初始化的過程中,而不像一般的依賴注入一樣發生在IoC容器初始化完成以后,第一次通過getBean想容器索要Bean的時候。
以上是“Spring IoC容器中依賴注入原理的示例分析”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。