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 lsr
- * @version Aug 17, 2011
- */
- 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());
- }
- }