参考文档:如有侵权,请联系本人删除。
一、基本用法示例:
如果你有两个具有很多相同属性的JavaBean:
@Data
public class CarDTO {
private Long id;
private String vin;
private double price;
private double totalPrice;
private Date publishDate;
private String color;
private String brand;
private List<PartDTO> partsDTOS;
private DriverDTO driverDTO;
}
public class CarVO {
private Long id;
private String vin;
private Double price;
private String totalPrice;
private String publishDate;
private String color;
private String brandName;
private Boolean hasPart;
private DriverVO deiverVO;
}
然后我们对CarDTO进行赋值
//初始化零件
//零件一
PartDTO partDtO1 = new PartDTO();
partDtO1.setPartId(1L);
partDtO1.setPartName("多功能方向盘");
//零件二
PartDTO partDtO2 = new PartDTO();
partDtO1.setPartId(2L);
partDtO1.setPartName("智能车门");
//填充至list中
List<PartDTO> partDTOList = new ArrayList<>();
partDTOList.add(partDtO1);
partDTOList.add(partDtO2);
//初始化司机
DriverDTO driverDTO = new DriverDTO();
driverDTO.setId(1L);
driverDTO.setName("王二狗");
//然后把初始化后的全部填充至实体中
CarDTO carDTO = new CarDTO();
carDTO.setId(330L);
carDTO.setVin("vin123456789");
carDTO.setPrice(123789.126d);
carDTO.setTotalPrice(143789.126d);
carDTO.setPublishDate(new Date());
carDTO.setColor("白色");
carDTO.setBrand("大众");
carDTO.setPartsDTOS(partDTOList);
carDTO.setDriverDTO(driverDTO);
这样我们就得到了初始化后的CarDTO,然后我们用beanUtils对CarVO进行赋值(此处用的是spring包下面的工具包)
CarDTO carDTO = buildCarDTO();
CarVO carVO = new CarVO();
BeanUtils.copyProperties(carDTO,carVO);//copyProperties(source, target)
System.out.println("=====CarVO========"+carVO.toString());
输出结果如下
id=330,
vin=vin123456789,
price=123789.126,
totalPrice=null,
publishDate=null,
color=白色,
brandName=null,
hasPart=null,
deiverVO=null
可以看到具有同一类型以及相同的属性名(基础类及包装类这里视为同一类型)都得到了复制,其实beanUtils可以满足大部分实体类间同名同类型的属性赋值,这里这个例子只是极端情况,剩下的属性(null)则需要手动进行赋值
CarDTO carDTO = buildCarDTO();
CarVO carVO = new CarVO();
BeanUtils.copyProperties(carDTO,carVO);
double totalPrice = carDTO.getTotalPrice();
DecimalFormat decimalFormat = new DecimalFormat("#.00");
carVO.setTotalPrice(decimalFormat.format(totalPrice));
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
carVO.setPublishDate(simpleDateFormat.format(carDTO.getPublishDate()));
carVO.setBrandName