Dozer是一个JavaBean到JavaBean之间的转换工具。它就可以递归的将数据从一个对象复制到另一个对象。
Dozer的官方文档:http://dozer.sourceforge.net/documentation/whymap.html
Dozer的github地址:https://github.com/DozerMapper/dozer
Dozer转换好处:
- 如果两个类型属性名称一致,不论类型是否一致。dozer都可以自动配置
- 如果类中有null property,dozer可以默认将属性指为null,不会抛出nullPointerExeception异常。
Dozer整合项目(有三种:xml形式/注解配置/API配置)
引入jar
<dependency>
<groupId>net.sf.dozer</groupId>
<artifactId>dozer</artifactId>
<version>5.4.0</version>
</dependency>
xml配置
- xml头部文件
<?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">
</mappings>
xml中mapping配置(将a中对应的属性名转换为b中对应的属性名,<a>标签转换为<b>标签)
<mapping>
<class-a>com.qding.brick.pojo.biz.Project</class-a>
<class-b>com.qding.openapi.call.stage.struct.Project</class-b>
<field>
<a>id</a>
<b>projectId</b>
</field>
<field>
<a>name</a>
<b>projectName</b>
</field>
<field>
<a>address</a>
<b>addr</b>
</field>
</mapping>
注:官网着重建议:在现实应用中,最好不要每次映射对象时都创建一个Mapper实例来工作,这样会产生不必要的开销。如果你不使用IoC容器(如:spring)来管理你的项目,那么,最好将Mapper定义为单例模式。
- 测试:
Mapper mapper = new DozerBeanMapper();
DestinationObject destObject = mapper.map(sourceObject, DestinationObject.class);
- 补充:单例模式例子
public class DozerMapperConstant {
private static final Mapper mapper= new org.dozer.DozerBeanMapper();
public static DozerBeanMapper getDozerBeanMapper() {
return mapper;
}
}
Mapper announcementDozerMapper = DozerMapperConstant.dozerMapper;
API方式
import static org.dozer.loader.api.FieldsMappingOptions.*;
import static org.dozer.loader.api.TypeMappingOptions.*;
...
BeanMappingBuilder builder = new BeanMappingBuilder() {
protected void configure() {
mapping(Bean.class, Bean.class,
TypeMappingOptions.oneWay(),
mapId("A"),
mapNull(true)
)
.exclude("excluded")
.fields("src", "dest",
copyByReference(),
collectionStrategy(true,
RelationshipType.NON_CUMULATIVE),
hintA(String.class),
hintB(Integer.class),
FieldsMappingOptions.oneWay(),
useMapId("A"),
customConverterId("id")
)
.fields("src", "dest",
customConverter("org.dozer.CustomConverter")
);
}
};
使用
DozerBeanMapper mapper = new DozerBeanMapper();
mapper.addMapping(builder);
注解方式 (mapping自动注入)
a类
public class SourceBean {
private Long id;
private String name;
@Mapping("binaryData")
private String data;
@Mapping("pk")
public Long getId() {
return this.id;
}
public String getName() {
return this.name;
}
}
b类
public class TargetBean {
private String pk;
private String name;
private String binaryData;
public void setPk(String pk) {
this.pk = pk;
}
public void setName(String name) {
this.name = name;
}
}