(spring-第11回【IoC基礎篇】)BeanWrapper--執行個體化Bean的第四大利器,beanwrapper
重複是理解和記憶的最好方法。在講執行個體化Bean的每個步驟之前,我都會先複習一下Bean執行個體化的整個過程:
結合圖片我們回顧一下具體的過程:
今天我們將介紹的就是第五步。開門見山,BeanWrapper的功能:
spring通過BeanWrapper完成屬性的配置工作。具體表現為:
下面是BeanWrapper的繼承結構:
從上面的結構可以看出,BeanWrapperImpl(BeanWrapper的實作類別)有兩個頂級介面,分別是:PropertyEditorRegistry和PropertyAccessor,前者是屬性編輯器,負責將設定檔中bean屬性的字面值轉換為bean具體的屬性值。後者定義了各種訪問bean屬性的方法。所以BeanWrapperImpl具有三重身份:
1. Bean包裹器:(顧名思義)
下面代碼是BeanWrapperImpl初始化時要執行的方法,而參數中的object就是包裹的bean對象。
其中第8行就是把object.getClass()儲存在cachedIntrospectionResults 屬性中,該屬性是CachedIntrospectionResults類的執行個體,
而CachedIntrospectionResults是負責緩衝屬性描述器(PropertyDescriptor)資訊的。
object是對象的執行個體,而object.getClass()則擷取的是執行個體對應的類的描述資訊,那麼cachedIntrospectionResults 拿到這個執行個體類的描述資訊class,就可以通過反射機制來訪問該class裡面的所有屬性了,最後封裝成PropertyDescriptor。
屬性描述器(PropertyDescriptor)是java.beans.PropertyDescriptor包裡的類,用來描述java bean的屬性(一個描述器描述一個屬性),這個屬性是JavaBean通過一對入口方法匯出的。
BeanWrapperImpl利用屬性描述器資訊結合屬性編輯器來設定屬性。
1 public void setWrappedInstance(Object object, String nestedPath, Object rootObject) {2 Assert.notNull(object, "Bean object must not be null");3 this.object = object;4 this.nestedPath = (nestedPath != null ? nestedPath : "");5 this.rootObject = (!"".equals(this.nestedPath) ? rootObject : object);6 this.nestedBeanWrappers = null;7 this.typeConverterDelegate = new TypeConverterDelegate(this, object);8 setIntrospectionClass(object.getClass());9 }
1 protected void setIntrospectionClass(Class clazz) {2 if (this.cachedIntrospectionResults != null &&3 !clazz.equals(this.cachedIntrospectionResults.getBeanClass())) {4 this.cachedIntrospectionResults = null;5 }6 }
2. 屬性訪問器:即PropertyAccessor,這個介面有很多方法,諸如:setPropertyValue、setPropertyValues等,BeanWrapperImpl通過這些方法來設定bean屬性的值。
3. 屬性編輯器註冊表:(負責取出屬性編輯器,BeanWrapperImpl結合屬性編輯器來設定屬性)。
下面是BeanWrapperImpl的某個建構函式,一開始就調用了從屬性編輯器那裡繼承過來的registerDefaultEditors方法,該方法自動註冊載入spring預設的屬性編輯器們。
1 public BeanWrapperImpl(Object object) {2 registerDefaultEditors();3 setWrappedInstance(object);4 }
BeanWrapperImpl完成Bean屬性的配置工作之後,接下來還需要Bean後處理器(實現了BeanPostProcessor介面的Bean)繼續對Bean執行個體進行加工,直到裝配出一個準備就緒的Bean,把肉放到碗裡等萌寶來吃。
由於本文未對代碼進行詳細解讀,所以其中會有沒有講到的地方,比如,屬性編輯器具體是怎樣的?如何對bean的屬性進行編輯?下一篇博文將會詳細介紹。