dozer- JavaBean對映工具

weixin_33850890發表於2017-05-27

1、簡介

dozer是一種JavaBean的對映工具,類似於apache的BeanUtils。但是dozer更強大,它可以靈活的處理複雜型別之間的對映。不但可以進行簡單的屬性對映、複雜的型別對映、雙向對映、遞迴對映等,並且可以通過XML配置檔案進行靈活的配置。

2、準備

現在開始就小試一下。 首先,需要下載jar包,
dozer.jar :http://dozer.sourceforge.net/downloading.html
還需要slf4j.jar,commons-lang.jar,commons-beanutil.jar, commons-loggin.jar

3、程式碼

兩個bean

public class Book {  
    private String name;  
    private String author;  
  
    public String getName() {  
        return name;  
    }  
  
    public void setName(String name) {  
        this.name = name;  
    }  
  
    public String getAuthor() {  
        return author;  
    }  
  
    public void setAuthor(String author) {  
        this.author = author;  
    }  
  
    public Book() {  
    }  
}  
public class BookVo {  
    private String namevo;  
    private String authorvo;  
  
    public String getNamevo() {  
        return namevo;  
    }  
  
    public void setNamevo(String namevo) {  
        this.namevo = namevo;  
    }  
  
    public String getAuthorvo() {  
        return authorvo;  
    }  
  
    public void setAuthorvo(String authorvo) {  
        this.authorvo = authorvo;  
    }  
  
    public BookVo() {  
    }  
} 

bookMapper.xml配置檔案,用來對DozerBeanMapper進行設定。

<?xml version="1.0" encoding="UTF-8"?>  
<mappings xmlns="http://dozer.sourceforge.net"  
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
       xsi:schemaLocation="http://dozer.sourceforge.net  
       http://dozer.sourceforge.net/schema/beanmapping.xsd">  
         
       <mapping>  
        <class-a>test.Book</class-a>  
        <class-b>test.BookVo</class-b>  
        <field>  
            <a>name</a>  
            <b>namevo</b>  
        </field>  
        <field>  
            <a>author</a>  
            <b>authorvo</b>  
        </field>  
       </mapping>  
 </mappings>  

測試類

package test;  
  
import java.util.ArrayList;  
import java.util.List;  
  
import org.apache.commons.logging.Log;  
import org.apache.commons.logging.LogFactory;  
import org.dozer.DozerBeanMapper;  
  
/** 
 * 說明: 
 *  
 * @author fredia
 * @version Aug 17, 2017
 */  
public class DozerTest {  
    /** 
     * @param args 
     */  
    public static void main(String[] args) {  
        testByXml();  
    }  
      
    public static void testByXml() {  
        Book book = new Book();  
        book.setAuthor("lsr");  
        book.setName("dozer demo");  
        DozerBeanMapper mapper = new DozerBeanMapper();  
        List<String> mappers = new ArrayList<String>();  
        mappers.add("bookMapper.xml");  
        mapper.setMappingFiles(mappers);  
        BookVo vo = new BookVo();  
        mapper.map(book, vo);  
        System.out.println("book's name:" + book.getName());  
        System.out.println("bookVo's name:" + vo.getNamevo());  
    }  
  
}  

相關文章