日常开发中,涉及到DO、DTO、VO对象属性拷贝赋值,需要大量重复set很浪费时间,为了提高效率找了一些方法
传统的get/set方法
public PersonDTO personToPersonDTO(Person person) {
if (person == null) {
return null;
}
PersonDTO personDTO = new PersonDTO();
personDTO.setName(person.getName());
personDTO.setAge(person.getAge());
return personDTO;
}
这种方式执行效率高,但是如果字段很多的情况下肯定是很费时,影响我们的开发效率
使用BeanUtil.copyProperties
for (AccountInfoDto accountInfoDto : accountInfoList) {
NoCashDirectLinkAccount noCashDirectLinkAccount = new NoCashDirectLinkAccount();
BeanUtils.copyProperties(accountInfoDto,noCashDirectLinkAccount);
noCashDirectLinkAccount.setStatus(StatusEnum.InsertOrdinal());
noCashDirectLinkAccount.setId(IdUtils.setNextStrId("NoCashDirectLinkAccount"));
directLinkAccounts.add(noCashDirectLinkAccount);
}
BeanUtils.copyProperties的底层原理是使用反射机制,将源对象的属性值复制到目标对象的对应属性中,不过方便
使用反射运行效率肯定是不高,而且还有些坑
- 字段类型和名字需要完全一样
- 使用lombok的话包装类和非包装类也无法进行转换
- 只是浅拷贝
使用映射工具库
如MapStruct、ModelMapper等
@Mapper
public interface SourceTargetMapper {
SourceTargetMapper INSTANCE = Mappers.getMapper(SourceTargetMapper.class);
@Mapping(source = "name", target = "name")
@Mapping(source = "age", target = "age")
Target mapToTarget(Source source);
}
//使用
Target target = SourceTargetMapper.INSTANCE.mapToTarget(source);
这种底层原理等同于get/set,但也要创建配置类