您好,登錄后才能下訂單哦!
本篇文章給大家分享的是有關在Spring中如何實現加載Bean的,小編覺得挺實用的,因此分享給大家學習,希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。
之前寫過bean的解析,這篇來講講bean的加載,加載要比bean的解析復雜些,從之前的例子開始.
Spring中加載一個bean的方式:
TestBean bean = factory.getBean("testBean");
來看看getBean(String name)方法源碼,
@Override public Object getBean(String name) throws BeansException { return doGetBean(name, null, null, false); }
該getBean(String name)方法位于AbstractBeanFactory抽象類中,AbstractBeanFactory與XmlBeanFactory類關系可以看下圖:
接下去跟進doGetBean()方法源碼:
protected <T> T doGetBean( final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly) throws BeansException { // 提取beanName final String beanName = transformedBeanName(name); Object 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 + "'"); } } // 返回實例,有時存在如BeanFactory這樣情況時并不是直接返回實例本身而是返回指定方法返回的實例 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); } // Check if bean definition exists in this factory. BeanFactory parentBeanFactory = getParentBeanFactory(); // 如果在所有已經加載的類中沒有beanName則會嘗試從parentBeanFactory中檢測 if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { // Not found -> check parent. String nameToLookup = originalBeanName(name); // 到BeanFactory查找 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) { markBeanAsCreated(beanName); } try { // 將存儲XML配置文件的GernericBeanDefinition轉換成RootBeanDefinition,如果BeanName是子Bean的話會合并父類的相關屬性 final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); checkMergedBeanDefinition(mbd, beanName, args); // Guarantee initialization of beans that the current bean depends on. String[] dependsOn = mbd.getDependsOn(); // 如果存在依賴的話要遞歸實例化依賴的bean if (dependsOn != null) { for (String dependsOnBean : dependsOn) { if (isDependent(beanName, dependsOnBean)) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Circular depends-on relationship between '" + beanName + "' and '" + dependsOnBean + "'"); } registerDependentBean(dependsOnBean, beanName); getBean(dependsOnBean); } } // Create bean instance. // 依賴的bean實例化完后就可以實例化mbd了 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); } 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 { // 在對應的scope上實例化bean String scopeName = mbd.getScope(); final Scope scope = this.scopes.get(scopeName); if (scope == null) { throw new IllegalStateException("No Scope registered for scope '" + 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; } } // 檢查需要的類型是否符合實例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; }
整個bean加載的過程步驟相對繁瑣,主要步驟有以下幾點:
1、轉換beanName
要知道平時開發中傳入的參數name可能只是別名,也可能是FactoryBean,所以需要進行解析轉換,一般會進行以下解析:
(1)消除修飾符,比如name="&test",會去除&使name="test";
(2)取alias表示的最后的beanName,比如別名test01指向名稱為test02的bean則返回test02。
2、從緩存中加載實例
實例在Spring的同一個容器中只會被創建一次,后面再想獲取該bean時,就會嘗試從緩存中獲取;如果獲取不到的話再從singletonFactories中加載。
3、實例化bean
緩存中記錄的bean一般只是最原始的bean狀態,這時就需要對bean進行實例化。如果得到的是bean的原始狀態,但又要對bean進行處理,這時真正需要的是工廠bean中定義的factory-method方法中返回的bean,上面源碼中的getObjectForBeanInstance就是來完成這個工作的。
4、檢測parentBeanFacotory
從源碼可以看出如果緩存中沒有數據會轉到父類工廠去加載,源碼中的!containsBeanDefinition(beanName)就是檢測如果當前加載的xml配置文件中不包含beanName所對應的配置,就只能到parentBeanFacotory去嘗試加載bean。
5、存儲XML配置文件的GernericBeanDefinition轉換成RootBeanDefinition之前的文章介紹過XML配置文件中讀取到的bean信息是存儲在GernericBeanDefinition中的,但Bean的后續處理是針對于RootBeanDefinition的,所以需要轉換后才能進行后續操作。
6、初始化依賴的bean
這里應該比較好理解,就是bean中可能依賴了其他bean屬性,在初始化bean之前會先初始化這個bean所依賴的bean屬性。
7、創建bean
Spring容器根據不同scope創建bean實例。
整個流程就是如此,下面會講解一些重要步驟的源碼。
上面有提到,單例在Spring中的同一容器中只會被創建一次,后面再獲取bean的話會直接從緩存中獲取,這里是嘗試加載,先從緩存中加載,再次就是從singletonFactories中加載;因為在bean中可能會在依賴注入,要避免循環依賴,Spring創建bean時會不等bean創建完成就會將創建該bean的ObjectFactory提前曝光加入到緩存中,但下一個bean創建時要依賴上個bean的話,就直接使用ObjectFacotry。
@Override public Object getSingleton(String beanName) { return getSingleton(beanName, true); // true表示允許早期依賴 } protected Object getSingleton(String beanName, boolean allowEarlyReference) { // 嘗試從緩存獲取實例 Object singletonObject = this.singletonObjects.get(beanName); if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) { synchronized (this.singletonObjects) { // 若該bean正在加載則不處理 singletonObject = this.earlySingletonObjects.get(beanName); if (singletonObject == null && allowEarlyReference) { ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName); if (singletonFactory != null) { singletonObject = singletonFactory.getObject(); // 存入到緩存中 this.earlySingletonObjects.put(beanName, singletonObject); this.singletonFactories.remove(beanName); } } } } return (singletonObject != NULL_OBJECT ? singletonObject : null); } /* 這兩個方法在DefaultSingletonBeanRegistry類中 */
從源碼可以看出這個方法先嘗試從singletonObjects中獲取實例,如果獲取不到值就從earlySingletonObject中去獲取,如果再獲取不到的話則到singletonFactories里獲取beanName對應的ObjectFactory,再調用這個ObjectFactory的getObject來創建bean,并放到earlySingletonObject中,并且從singletonFactories里remove掉這個ObjectFactory。這里有幾個存儲bean的不同map:
如果上面緩存中不存在已經加載的單例bean就要重新開始bean的加載過程了,Spring中使用getSingleton重載方法實現bean的加載過程。
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) { Assert.notNull(beanName, "'beanName' must not be null"); synchronized (this.singletonObjects) { // 先檢查bean是否已經加載 Object singletonObject = this.singletonObjects.get(beanName); // 如果空才進行singleton的bean的初始化 if (singletonObject == null) { if (this.singletonsCurrentlyInDestruction) { throw new BeanCreationNotAllowedException(beanName, "Singleton bean creation not allowed while the singletons of this factory are in destruction " + "(Do not request a bean from a BeanFactory in a destroy method implementation!)"); } if (logger.isDebugEnabled()) { logger.debug("Creating shared instance of singleton bean '" + beanName + "'"); } beforeSingletonCreation(beanName); boolean newSingleton = false; boolean recordSuppressedExceptions = (this.suppressedExceptions == null); if (recordSuppressedExceptions) { this.suppressedExceptions = new LinkedHashSet<Exception>(); } try { // 初始化bean singletonObject = singletonFactory.getObject(); newSingleton = true; } catch (IllegalStateException ex) { // Has the singleton object implicitly appeared in the meantime -> // if yes, proceed with it since the exception indicates that state. singletonObject = this.singletonObjects.get(beanName); if (singletonObject == null) { throw ex; } } catch (BeanCreationException ex) { if (recordSuppressedExceptions) { for (Exception suppressedException : this.suppressedExceptions) { ex.addRelatedCause(suppressedException); } } throw ex; } finally { if (recordSuppressedExceptions) { this.suppressedExceptions = null; } afterSingletonCreation(beanName); } if (newSingleton) { // 存入緩存 addSingleton(beanName, singletonObject); } } return (singletonObject != NULL_OBJECT ? singletonObject : null); } }
這段代碼使用了回調方法,使程序可以在單例創建的前后做一些準備及處理操作,真正的獲取單例bean的方法其實并不是在這個方法實現的,而是在ObjectFactory類型的實例singletonFactory中實現的。
下面準備創建bean
看看createBean()方法源碼(該方法在AbstractAutowireCapableBeanFactory類中):
protected Object createBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) throws BeanCreationException { if (logger.isDebugEnabled()) { logger.debug("Creating instance of bean '" + beanName + "'"); } // 鎖定class,根據設置的class屬性或根據className來解析Class resolveBeanClass(mbd, beanName); // 驗證和準備覆蓋的方法 try { mbd.prepareMethodOverrides(); } catch (BeanDefinitionValidationException ex) { throw new BeanDefinitionStoreException(mbd.getResourceDescription(), beanName, "Validation of method overrides failed", ex); } try { // 用BeanPostProcessors返回代理來替代真正的實例 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); } Object beanInstance = doCreateBean(beanName, mbd, args); if (logger.isDebugEnabled()) { logger.debug("Finished creating instance of bean '" + beanName + "'"); } return beanInstance; }
從createBean()方法源碼可以看出主要做了以下操作:
在createBean()方法里執行完resolveBeforeInstantiation方法后,如果創建了代理且不為空的話就直接返回,否則需要進行常規bean的創建,這個創建過程是在doCreateBean中完成的,跟進源碼:
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) { // Instantiate the bean. BeanWrapper instanceWrapper = null; if (mbd.isSingleton()) { instanceWrapper = this.factoryBeanInstanceCache.remove(beanName); } 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; } } // 檢測循環依賴,是否需要提早曝光 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再次依賴引用 // AOP也是在這里將advice動態織入bean中,若沒有則直接返回bean,不做處理 return getEarlyBeanReference(beanName, mbd, bean); } }); } // Initialize the bean instance. Object exposedObject = bean; try { // 填充bean,注入屬性值,如果存在依賴于其他bean的屬性,會遞歸初始化 populateBean(beanName, mbd, instanceWrapper); if (exposedObject != null) { // 調用初始化方法 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 = 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); } } 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 { // 依據scopse注冊bean registerDisposableBeanIfNecessary(beanName, bean, mbd); } catch (BeanDefinitionValidationException ex) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex); } return exposedObject; }
上面源碼完成的操作可以概括為以下幾點:
接下來創建bean實例,看createBeanInstance()方法:
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, Object[] args) { // 解析class 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()); } // 若工廠方法不為空則使用工廠方法初始化 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); } } // 根據參數解析構造方法 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); }
可以看出如果在RootBeanDefinition中存在factoryMethodName屬性,或者說配置文件中配置了factory-method,那么Spring會嘗試使用instantiateUsingFactoryMethod(beanName, mbd, args)方法根據RootBeanDefinition中的配置生成bean實例。
再解析構造方法并進行實例化,Spring會根據參數及類型判斷使用哪個構造方法再進行實例化。判斷調用哪個構造方法的過程會采用緩存機制,如果已經解析過則不需要重復解析而是從RootBeanDefinition中的屬性resolvedConstructorOrFactoryMethod緩存的值去取,不然則需要再次解析。
創建bean后接下來就進行屬性注入,屬性注入的操作在populateBean()方法中,跟進源碼:
protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) { PropertyValues pvs = mbd.getPropertyValues(); if (bw == null) { if (!pvs.isEmpty()) { throw new BeanCreationException( mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance"); } else { // Skip property population phase for null instance. return; } } // Give any InstantiationAwareBeanPostProcessors the opportunity to modify the // state of the bean before properties are set. This can be used, for example, // to support styles of field injection. boolean continueWithPropertyPopulation = true; if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof InstantiationAwareBeanPostProcessor) { InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp; if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) { continueWithPropertyPopulation = false; break; } } } } if (!continueWithPropertyPopulation) { return; } if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME || mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) { MutablePropertyValues newPvs = new MutablePropertyValues(pvs); // Add property values based on autowire by name if applicable. if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) { autowireByName(beanName, mbd, bw, newPvs); } // Add property values based on autowire by type if applicable. if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) { autowireByType(beanName, mbd, bw, newPvs); } pvs = newPvs; } boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors(); boolean needsDepCheck = (mbd.getDependencyCheck() != RootBeanDefinition.DEPENDENCY_CHECK_NONE); if (hasInstAwareBpps || needsDepCheck) { PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching); if (hasInstAwareBpps) { for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof InstantiationAwareBeanPostProcessor) { InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp; pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName); if (pvs == null) { return; } } } } if (needsDepCheck) { checkDependencies(beanName, mbd, filteredPds, pvs); } } applyPropertyValues(beanName, mbd, bw, pvs); }
在populateBean方法的中的主要處理流程:
最后初始化bean
學過Spring的都知道bean配置時有一個init-method屬性,這個屬性的作用是在bean實例化前調用init-method指定的方法進行需要的實例化操作,現在就進入這個方法了;Spring中程序已經執行過bean的實例化,并且進行了屬性的填充,而就在這時將會調用用戶設定的初始化方法。
protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) { if (System.getSecurityManager() != null) { AccessController.doPrivileged(new PrivilegedAction<Object>() { @Override public Object run() { invokeAwareMethods(beanName, bean); return null; } }, getAccessControlContext()); } else { // 特殊bean處理 invokeAwareMethods(beanName, bean); } Object wrappedBean = bean; if (mbd == null || !mbd.isSynthetic()) { wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName); } try { invokeInitMethods(beanName, wrappedBean, mbd); } catch (Throwable ex) { throw new BeanCreationException( (mbd != null ? mbd.getResourceDescription() : null), beanName, "Invocation of init method failed", ex); } if (mbd == null || !mbd.isSynthetic()) { wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName); } return wrappedBean; }
最后加載完Bean并執行完初始化操作后,一個bean的加載基本就結束了。
以上就是在Spring中如何實現加載Bean的,小編相信有部分知識點可能是我們日常工作會見到或用到的。希望你能通過這篇文章學到更多知識。更多詳情敬請關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。