细心比对,发现原来是导错了包导致的
正确的包
import org.springframework.beans.BeanUtils;
错误的包
import org.apache.commons.beanutils.BeanUtils;
两个类的区别
-
两者的copyProperties方法参数位置不同org.springframework.beans.BeanUtils: copyProperties(sourceDemo, targetDemo)
org.apache.commons.beanutils.BeanUtils: copyProperties(targetDemo, sourceDemo) -
要求两个Bean的属性名相同,且有对应的setXxx方法和getXxx方法。其实底层原理是使用sourceDemo的getXxx方法和targetDemo的setXxx方法
-
sourceDemo有的属性而targetDemo没有的属性,不会封装到targetDemo对象中;targetDemo有的属性而sourceDemo没有的属性,会封装到targetDemo中,数据为默认值(注意基本类型默认值与引用类型默认值不同)
-
类型转换问题
基本类型与其对应的封装类型可以相互转换
org.springframework.beans.BeanUtils与org.apache.commons.beanutils.BeanUtils对于String和Date类型转换的情况是不同的
总结
发现其实只需要将两个对象换个位置就好了。。。