`

对象转换利器之Dozer

 
阅读更多
在Java的世界中,经常会涉及到需要在2个对象中进行转换,比如说:
  • 调用SOAP Web服务,需要把自己的Domain对象转换为Soap服务的Jaxb对象请求,
  • 在分层级SOA架构中,2个层级之间Domain对象的转换,
  • 在分布式系统中,每个模块使用自己的领域对象,防止自己的业务被其他模块的domain对象影响

通常情况下,程序员们会自己弄一个Transformer层,来做对象之间的转换。估计很多同志在自己的项目代码中都可以看到Transformer的身影。但是,复杂的Java对象之间的转换并不是一个非常容易的问题,因为你需要不停的检测某个属性值是否为null,你需要做属性类型的转换,Date对应到String, String对应到Int等等。这就导致了Transformer的臃肿以及对程序员生产力的浪费。Dozer就是对懒(you)惰(xiu)程序员在这个问题上的通用解决方案。

Dozer是一个开源的,通用的,健壮的,灵活的,易于重用的,可配置的Java对象Mapping框架 。这个定义中的每一个形容词对程序员都非常亲切. (作者注: Dozer虽好,请不要贪恋, 因为任何对象之间的转换都会带来维护和性能的开销,能不做对象转换还是不要做了,跑不掉的时候,请选用Dozer)。

Dozer怎么用
使用Dozer的流程非常清楚:
  • 配置你需要mapping的类,以及类之间的属性之间的对应关系。
  • 根据你的配置初始化Mapper
  • 使用mapper.map(source, target.class)获取转换后的对象。
Dozer提供了2种方式去配置需要mapping的类,一种是基于XML,一种是基于API,API的方式是5.3版本才开始提供的,主要是为了解决xml方式不可动态修改mapping配置的问题。下面来看一个最基础的使用Dozer的例子:

假设在一个系统中,模块A中客户的类型是User,而模块B中客户的类型是Customer, 现在模块B需要接受模块A中客户,并转换为自己模块的客户类型Customer。
public class User {
    private int userId;
    private String  userName;

    public User(int userId, String userName) {
        this.userId = userId;
        this.userName = userName;
    }

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }
}

public class Customer {

    private int customerId;
    private String customerName;

    public int getCustomerId() {
        return customerId;
    }

    public String getCustomerName() {
        return customerName;
    }

    public void setCustomerId(int customerId) {
        this.customerId = customerId;
    }

    public void setCustomerName(String customerName) {
        this.customerName = customerName;
    }
}

配置User和Customer属性的之间的对应关系
<?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">dia
    <mapping>
        <class-a>com.xianlinbox.dozer.source.User</class-a>
        <class-b>com.xianlinbox.dozer.destination.Customer</class-b>
        <field>
            <a>userId</a>
            <b>customerId</b>
        </field>
        <field>
            <a>userName</a>
            <b>customerName</b>
        </field>
    </mapping>
</mappings>

调用Mapper获取转换后的对象:
public class DozerMapperTest {
    private DozerBeanMapper mapper;

    @Before
    public void setUp() throws Exception {
        mapper = new DozerBeanMapper();
        mapper.setMappingFiles(Arrays.asList("dozer-bean-mappings.xml"));
    }

    @Test
    public void testMapping() throws Exception {
        User user = new User(1, "user1");
        Customer customer = mapper.map(user, Customer.class);
        assertThat(customer.getCustomerId(),equalTo(1));
        assertThat(customer.getCustomerName(),equalTo("user1"));
    }
}


Dozer做对象转换有什么特点
  • 默认属性Mapping,即如果属性名称一样, 就不需要显示配置,Dozer会自动处理。
  • 自动做类型转换,即如果两个属性名称一样,即使类型不一样,在Dozer可理解范围内,帮你处理得妥妥的。Dozer可理解的类型范围非常广,这会极大的提升程序员的生产力
  • 不必担心中间的null property,遇到null property,Dozer会把对应的所有属性全部设置为null,而不会抛NullPointerExeception。


Dozer可理解的类型转换有:
• Primitive to Primitive Wrapper
• Primitive to Custom Wrapper
• Primitive Wrapper to Primitive Wrapper
• Primitive to Primitive
• Complex Type to Complex Type
• String to Primitive
• String to Primitive Wrapper
• String to Complex Type if the Complex Type contains a String constructor
• String to Map
• Collection to Collection
• Collection to Array
• Map to Complex Type
• Map to Custom Map Type
• Enum to Enum
• Each of these can be mapped to one another: java.util.Date, java.sql.Date, java.sql.Time, java.sql.Timestamp, java.util.Calendar, java.util.GregorianCalendar
• String to any of the supported Date/Calendar Objects.
• Objects containing a toString() method that produces a long representing time in (ms) to any supported Date/Calendar object.

Dozer官网地址:http://dozer.sourceforge.net/
0
0
分享到:
评论
4 楼 sucheng2016 2016-10-17  
这东东真的好用么/
3 楼 jackyrong 2015-02-28  
更新了,14年5.5.1版本
2 楼 ningandjin 2013-12-20  
江南白衣 写道
可惜它好久不更新了。

是啊,一年没动了。好在当前的功能已经可以解决了我很大一坨的代码问题了。白衣兄的SpringSide有把它打包进去吗?
1 楼 江南白衣 2013-12-19  
可惜它好久不更新了。

相关推荐

    dozer的eclipse插件

    4. **预览与测试**: 在编辑过程中,你可以实时预览映射结果,查看对象转换的效果,这有助于调试和优化映射逻辑。 ### 提升开发效率 1. **自动化代码生成**: Dozer插件可以自动生成所需的映射方法,减少手动编码的...

    dozer5.3.2

    《Dozer 5.3.2:Java数据映射与校验利器》 在Java开发领域,数据转换和校验是常见的任务,尤其在处理不同系统间的数据交换时。Dozer是一个强大的开源库,专为解决此类问题而设计。本文将深入探讨Dozer 5.3.2版本的...

    解析网页利器组合(正则、jsoup、beanshell、dozer)资源

    在网页解析后,数据通常会以原始的Java对象形式存在,而Dozer可以帮助我们将这些对象转换成业务逻辑所需的格式,或者与数据库、JSON或其他数据格式进行交互。这在数据处理和集成过程中非常实用,可以减少手动编码的...

    BeanUtils工具包

    总结,BeanUtils工具包是Java开发中的一个利器,尤其在处理表单数据和对象属性映射时。熟练掌握BeanUtils的使用,能有效地提升代码的简洁性和可维护性,提高开发效率。然而,根据具体项目需求,也可能需要结合其他...

    BeanUtils-jar包

    为了处理这种情况,Apache Commons提供了另一个类似的包——`Dozer`,它提供了更智能的类型转换机制。 另外,BeanUtils-jar包还包含了一些其他有用的工具,如`DescriptorUtils`和`IntrospectorUtils`,它们可以帮助...

Global site tag (gtag.js) - Google Analytics