@Component
public class GetSetAssembler implements IAssembler<UserVO, UserDTO>{
@Override
public UserDTO sourceToTarget(UserVO var){
UserDTO userDTO = new UserDTO();
userDTO.setUserId(var.getUserId());
userDTO.setUserNickName(var.getUserNickName());
userDTO.setCreateTime(var.getCreateTime());
return userDTO;}}
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
推荐:★★★☆☆
性能:★★★★★
手段:手写
点评:其实这种方式也是日常使用的最多的,性能肯定是杠杠的,就是操作起来有点麻烦。尤其是一大堆属性的 VO 对象转换为 DTO 对象时候。但其实也有一些快捷的操作方式,比如你可以通过 Shift+Alt 选中所有属性,Shift+Tab 归并到一列,接下来在使用 Alt 选中这一列,批量操作粘贴userDTO.set以及快捷键大写属性首字母,最后切换到结尾补充括号和分号,最终格式化一下就搞定了。
2. json2Json
@Component
public class Json2JsonAssembler implements IAssembler<UserVO, UserDTO>{
@Override
public UserDTO sourceToTarget(UserVO var){
String strJson = JSON.toJSONString(var);
return JSON.parseObject(strJson, UserDTO.class);}}
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
推荐:☆☆☆☆☆
性能:★☆☆☆☆
手段:把对象转JSON串,再把JSON转另外一个对象
点评:这么写多半有点烧!
3. Apache copyProperties
@Component
public class ApacheCopyPropertiesAssembler implements IAssembler<UserVO, UserDTO>{
@Override
public UserDTO sourceToTarget(UserVO var){
UserDTO userDTO = new UserDTO();
try {
BeanUtils.copyProperties(userDTO, var);} catch (IllegalAccessException | InvocationTargetException e){
e.printStackTrace();}
return userDTO;}}
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
推荐:☆☆☆☆☆
性能:★☆☆☆☆
手段:Introspector 机制获取到类的属性来进行赋值操作
点评:有坑,兼容性交差,不建议使用
4. Spring copyProperties
@Component
public class SpringCopyPropertiesAssembler implements IAssembler<UserVO, UserDTO>{
@Override
public UserDTO sourceToTarget(UserVO var){
UserDTO userDTO = new UserDTO();
BeanUtils.copyProperties(var, userDTO);
return userDTO;}}
@Component
public class ModelMapperAssembler implements IAssembler<UserVO, UserDTO>{
private static ModelMapper modelMapper = new ModelMapper();
static {
modelMapper.addMappings(new PropertyMap<UserVO, UserDTO>(){
@Override
protected void configure(){// 属性值不一样可以自己操作
map().setUserId(source.getUserId());}});}
@Override
public UserDTO sourceToTarget(UserVO var){
return modelMapper.map(var, UserDTO.class);}}
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
官网:http://modelmapper.org
推荐:★★★☆☆
性能:★★★☆☆
手段:基于ASM字节码实现
点评:转换对象数量较少时性能不错,如果同时大批量转换对象,性能有所下降
11. JMapper
JMapper<UserDTO, UserVO> jMapper = new JMapper<>(UserDTO.class, UserVO.class, new JMapperAPI().add(JMapperAPI.mappedClass(UserDTO.class).add(JMapperAPI.attribute("userId").value("userId")).add(JMapperAPI.attribute("userNickName").value("userNickName")).add(JMapperAPI.attribute("createTime").value("createTime"))));