问题描述:
上代码:
public void saveDB(Student student) {
Student stu = new Student();
BeanUtils.copyProperties(student, stu);
String name = stu.getName();
}
在程序测试时发现,name始终获取不到,而实际上对象student这个变量name是有值的。
分析
排查发现BeanUtil引用了Spring框架自带的jar包,查看源码才发现了里面的坑。而平时一直用的是apache的jar包。
BeanUtil.copyProperties有两个jar包,但是两个jar包拷贝参数是相反的。
Spring框架自带的BeanUtil.copyProperties:
public static void copyProperties(Object source, Object target) throws BeansException {
//source 源文件,target 目标文件
copyProperties(source, target, (Class)null, (String[])null);
}
BeanUtils提供的org.apache.commons.beanutils.BeanUtils:
public static void copyProperties(Object dest, Object orig) throws IllegalAccessException, InvocationTargetException {
//destination,目标文件,original原始的,源文件
BeanUtilsBean.getInstance().copyProperties(dest, orig);
}
所以在开发时要格外注意引入的jar。
BeanUtil.copyProperties复制非空的字段:
BeanUtil.copyProperties(voiceToEsDto, dbRecord, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));