首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

Bean Mapping Utils-Dozer初探

2012-11-07 
Bean Mapping Utils--Dozer初探最近从springside3项目里看到个值对象拷贝框架 dozer 学习了一下,发现还是

Bean Mapping Utils--Dozer初探

最近从springside3项目里看到个值对象拷贝框架 dozer 学习了一下,发现还是满有用的,写点学习小结

适用情况:分层架构时对DTO,VO,Pojo之间值属性的拷贝,并且这种拷贝可以跨属性的,即两个对象可以完全不一样(字段名称,字段属性)

比如将基本类型转为包装类型,数组转字符串,各种Collection集合类型之间互相转化,举个例子页面有个产品form有个关键词属性 是个String数组,对应页面一排输入框,而在数据库里是用逗号(,)分隔的字符串,一般都是在程序里用

String.split(","),StringUtils.join(String[]s)这样的方法进行转化,现在将这两个互相转化的方法定义的pojo中

<!DOCTYPE mappings PUBLIC "-//DOZER//DTD MAPPINGS//EN"
"http://dozer.sourceforge.net/dtd/dozerbeanmapping.dtd">
<mappings>
<configuration>
<stop-on-errors>true</stop-on-errors>
<date-format>yyyy-MM-dd</date-format>
<wildcard>true</wildcard>
<trim-strings>true</trim-strings>
</configuration>
<mapping map-null="false">
<class-a>com.spring.bean.Students</class-a>
<class-b>com.spring.view.command.StudentCommand</class-b>
<field>
<a>word</a>
<b set-method="setWords(java.lang.String)" get-method="getWords">keyWords</b>
</field>
</mapping>
</mappings>

?测试代码

stu.setId("dd");
stu.setDate(new Date());
stu.setWord("1,2,3,4,5,6");
StudentCommand studentCommand = (StudentCommand) dozer.map(stu,
StudentCommand.class);
out.println(ReflectionToStringBuilder.toString(studentCommand));
StudentCommand sc1 = new StudentCommand();
sc1.setAge("444");
sc1.setName("");
sc1.setValue(5555);
sc1.setDate("2008-08-08");
sc1.setKeyWords(new String[] { "a", "b", "c", "d", "e", "f" });
Students stu1 = (Students) dozer.map(sc1, Students.class);
out.println(ReflectionToStringBuilder.toString(stu1));
String s=stu1.getWord();
out.println(stu1.getWord());
}

?

控制台输出

另外dozer也可格式化时间

<date-format>yyyy-MM-dd</date-format>
date=2008-06-03

sc1.setDate("2008-08-08");

date=Fri Aug 08 00:00:00 CST 2008

若两个需要互相拷贝的java对象有相同的字段名,则在配置文件中无需在指出就可以自带的copy,很方便

在程序里再也不用出现一堆的setXXX(XXX.getXXX)了

最后是spring的context文件

<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.5.xsd">
<bean id="net.sf.dozer.util.mapping.MapperIF"
scope="singleton">
<property name="mappingFiles">
<list>
<value>dozer-bean-mapping.xml</value>
</list>
</property>
</bean>
</beans>

?

热点排行