分析多層架構的JEE系統,經常存在JavaBean直接的拷貝。比如在DAO層,我們通過POJO取得業務層需要的數據,將這些數據傳遞給Service層的VO。POJO與VO就存在典型的值拷貝。還有就是Webservice,客戶端調用Webservice,也存在將大量返回值映射到相應的JavaBean里。呵呵 我們項目就是這個需求。
典型的解決方案就是手動拷貝,弊端很明顯,代碼中充斥大量Set Get方法,真正的業務沒埋藏與值的拷貝之中。另一種方案就是使用BeanUtil,但BeanUtil不夠很好的靈活性,又時候還不得不手動拷貝。
對于這種重復沒有實際意義的拷貝難道沒有終結解決方案嗎?! Dozer 一把JavaBean利器。(http://dozer.sourceforge.net/)
什么是Dozer?
看看官方的定義:
Dozer is a Java Bean to Java Bean mapper that recursively copies data from one object to
another. Typically, these Java Beans will be of different complex types.
Dozer supports simple property mapping, complextype mapping, bi-directional mapping, implicitexplicit mapping, as well as recursive
mapping.This includes mapping collection attributes that also need mapping at the element level.
注意:Dozer支持簡單類型 復雜類型的雙向遞歸映射。
如何使用呢? 類似BeanUtil 很簡單,如果兩個javaBean之間,屬性名相同,類型為基本類型,那么下面代碼就OK了,基本沒有學習曲線。
Mapper mapper = new DozerBeanMapper();
DestinationObject destObject = mapper.map(sourceObject, DestinationObject.class);
or
DestinationObject destObject = new DestinationObject();
mapper.map(sourceObject, destObject);
在后續的的內容中,我會介紹如何配置復雜的Map,如何自定義Map,如何獲得Map的統計數據等。JavaBean之間拷貝利器-Dozer(2) 映射數據類型不一致,級聯映射與自定義映射