简介
dozer是一种JavaBean的映射工具,类似于Apache的BeanUtils。它可以灵活地处理复杂类型之间的映射。不但可以进行简单的属性映射、复杂的类型映射、双向映射、递归映射等,并且可以通过XML配置文件进行灵活的配置。
DTO(数据传输对象)表现层与应用层之间是通过数据传输对象(DTO)进行交互的,数据传输对象的目的是为了对领域对象进行数据封装,实现层与层之间的数据传递。为什么不直接将领域对象用于数据传递?因为领域对象更注重领域,而DTO更注重数据,而且由于"富领域模型"的特点,这样会直接将领域对象的行为暴露给表现层。数据传输对象DTO本身并不是业务对象。数据传输对象是根据UI的需求进行设计的,而不是根据领域对象进行设计的。比如,Customer领域对象可能会包含一些诸如FirstName, LastName, Email, Address等信息。但如果UI上不打算显示Address的信息,那么CustomerDTO中也无需包含这个 Address的数据。简单地说Model面向业务,而我们是通过业务来定义Model的。DTO是面向界面UI,是通过UI的需求来定义的。通过DTO实现了表现层与Model之间的解耦,表现层不引用Model,如果开发过程中模型改变了而界面没改变,而我们只需要改Model而不需要去改表现层中的东西。
安装
使用maven,添加如下依赖到pom.xml:
<dependency>
<groupId>net.sf.dozer</groupId>
<artifactId>dozer</artifactId>
<version>5.5.1</version>
</dependency>
为什么要配置映射配置?
如果要映射的两个对象有完全相同的属性名,则只需要直接使用Dozer的API即可:
Mapper mapper = new DozerBeanMapper();
DestinationObject destObject =
mapper.map(sourceObject, DestinationObject.class);
但是实际映射时,往往存在属性名不同的情况。则需要添加配置来告诉Dozer应该怎样转换。在现实应用中最好不要每次映射对象时都创建一个Mapper实例来工作,这样会产生不必要的开销。如果不使用IoC容器(Spring)来管理,则最好将Mapper定义为单例模式。
配置映射配置文件
<mapping>标签中允许定义<class-a>和<class-b>,对应着相互映射的类。<field>标签里定义要映射的特殊属性。需要注意<a>和<class-a>对应,<b>和<class-b>对应。
<?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 date-format="yyyy-MM-dd">
<class-a>org.jie.spring.common.dozer.vo.NotSameAttributeA</class-a>
<class-b>org.jie.spring.common.dozer.vo.NotSameAttributeB</class-b>
<field>
<a>name</a>
<b>value</b>
</field>
</mapping>
</mappings>
与Spring整合
配置DozerBeanMappingFactoryBean
Dozer与Spring整合,只需要声明一个DozerBeanMapperFactoryBean,将所有的dozer映射配置文件作为属性注入到mappingFiles,DozerBeanMapperFactoryBean会加载这些规则。
添加spring-dozer.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd"
default-autowire="byName" default-lazy-init="false">
<bean id="mapper" class="org.dozer.spring.DozerBeanMapperFactoryBean">
<property name="mappingFiles">
<list>
<value>classpath*:dozer/dozer-mapping.xml</value>
</list>
</property>
</bean>
</beans>
这样只需要自动装配mapper即可使用:
@ContextConfiguration(locations = {"classpath:spring/spring-dozer.xml"})
public class DozerTest extends TestCase {
@Autowired
Mapper mapper;
public void testNotSameAttributeMapping(){
NotSameAttributeA src = new NotSameAttributeA();
src.setId(001);
src.setName("tester");
src.setDate(new Date());
NotSameAttributeB desc = mapper.map(src, NotSameAttributeB.class);
}
}
参考地址:
http://www.cnblogs.com/jingmoxukong/p/5952447.html?utm_source=gold_browser_extension