Spring 的 BeanUtils 的 copyProperties 方法需要注意的点

2019 年 10 月 10 日 ImportNew

(给ImportNew加星标,提高Java技能)

转自:简书,作者:绝色天龙

www.jianshu.com/p/357b55852efc


背景


最近项目中在和第三方进行联调一个接口,我们这边发送http请求给对方,然后接收对方的回应,代码都是老代码。


根据注释,对方的SDK中写好的Request类有一个无法序列化的bug,所以这边重新写了一个Request类,基本属性都是相同的,但是重点是有一个属性是静态内部类,还有两个是list属性


类似于下面这样:


private List orders;
private AddRequest.Ticket ticket;
private List payments;


AddRequest就是我们自己重写的请求类,他们SDK中的请求类是MixAddRequest,我们组装好请求参数后利用Spring的BeanUtils的copyProperties方法将AddRequest中的属性拷贝到MixAddRequest,然后发送请求。


到此为止,照理说一切完美!


结果请求失败,纳尼?对方说缺少一个必要的字段,参数校验不通过!


一查字段名称,是Ticket这个类里面的某个字段,赶紧看代码,心里充满对老代码的自信,想着一定是哪里搞错了,或者是他们那边偷偷动了代码,把字段从可选改为了必选,嘿嘿


果然在代码里找到了设置的地方,这下应该是他们的问题确信无疑了,再开一把调试,准备宣判他们的死刑。


结果发现发给他们的请求就是没有这个字段。。。中间只有一个Spring的copy属性的方法,当时觉得很诡异


由于中间只有这么一行代码,玄机肯定在这里面,初步怀疑是两个静态内部类不同导致,所以自己写Demo,准备搞一把这个BeanUtils的copyProperties方法


写了两个类和一个Main,@Data和@ToString是lombok插件的注解,这里用来自动生成getter和setter方法以及toString方法


@ToString
@Data
public class CopyTest1 {
public String outerName;
public CopyTest1.InnerClass innerClass;
public List clazz;

@ToString
@Data
public static class InnerClass {
public String InnerName;
}
}


@ToString
@Data
public class CopyTest2 {
public String outerName;
public CopyTest2.InnerClass innerClass;
public List clazz;

@ToString
@Data
public static class InnerClass {
public String InnerName;
}
}


CopyTest1 test1 = new CopyTest1();
test1.outerName = "hahaha";
CopyTest1.InnerClass innerClass = new CopyTest1.InnerClass();
innerClass.InnerName = "hohoho";
test1.innerClass = innerClass;

System.out.println(test1.toString());
CopyTest2 test2 = new CopyTest2();
BeanUtils.copyProperties(test1, test2);

System.out.println(test2.toString());


这里遇到了第一个坑,一开始图省事,属性写为public,想着省掉了getter和setter方法,没加@Data注解


结果运行完test2所有属性都为null,一个都没copy过去。加上@Data继续跑,果然,基本属性(String)复制过去了,但是内部类在test2中还是null。


那就验证了真的是内部类的问题,有点不敢相信自己的眼睛,毕竟线上跑了这么久的代码。。。


知道了问题,总要想着怎么解决吧,所以需要单独设置一下内部类,单独copy


如果内部类的bean属性较多或者递归的bean属性很多,那可以自己封装一个方法,用于递归拷贝,我这里只有一层,所以直接额外copy一次


CopyTest1 test1 = new CopyTest1();
test1.outerName = "hahaha";
CopyTest1.InnerClass innerClass = new CopyTest1.InnerClass();
innerClass.InnerName = "hohoho";
test1.innerClass = innerClass;

System.out.println(test1.toString());
CopyTest2 test2 = new CopyTest2();
test2.innerClass = new CopyTest2.InnerClass();
BeanUtils.copyProperties(test1, test2);
BeanUtils.copyProperties(test1.innerClass, test2.innerClass);

System.out.println(test2.toString());


记得内部类的属性也是要有setter方法的,不然也会导致copy失败,大家还记得我开头说到还有两个List属性的吧,为什么要提到这个呢?你猜


其实list里面的两个类也都是重写的内部类,他们也是不同的,当时他们却顺利copy过去了


为什么呢?因为java的泛型只在编译期起作用,在运行期,list属性就是一个存放Object的集合


在copy后,MixAddRequest的orders属性其实是一个Order类的集合,但却不是自己内部类的集合,是AddRequest的内部类Order的集合,但因为对方是解析json的,所以没有发生错误。。。


总结


  1. Spring的BeanUtils的CopyProperties方法需要对应的属性有getter和setter方法;

  2. 如果存在属性完全相同的内部类,但是不是同一个内部类,即分别属于各自的内部类,则spring会认为属性不同,不会copy;

  3. 泛型只在编译期起作用,不能依靠泛型来做运行期的限制;

  4. 最后,spring和apache的copy属性的方法源和目的参数的位置正好相反,所以导包和调用的时候都要注意一下。


最后的最后


附上spring的源码,getWriteMethod是jdk的方法,会去取set开头的方法,所以没有setter方法是不行滴。


private static void copyProperties(Object source, Object target, @Nullable Class<?> editable, @Nullable String... ignoreProperties) throws BeansException {
Assert.notNull(source, "Source must not be null");
Assert.notNull(target, "Target must not be null");
Class<?> actualEditable = target.getClass();
if (editable != null) {
if (!editable.isInstance(target)) {
throw new IllegalArgumentException("Target class [" + target.getClass().getName() + "] not assignable to Editable class [" + editable.getName() + "]");
}

actualEditable = editable;
}

PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);
List<String> ignoreList = ignoreProperties != null ? Arrays.asList(ignoreProperties) : null;
PropertyDescriptor[] var7 = targetPds;
int var8 = targetPds.length;

for(int var9 = 0; var9 < var8; ++var9) {
PropertyDescriptor targetPd = var7[var9];
Method writeMethod = targetPd.getWriteMethod();
if (writeMethod != null && (ignoreList == null || !ignoreList.contains(targetPd.getName()))) {
PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
if (sourcePd != null) {
Method readMethod = sourcePd.getReadMethod();
if (readMethod != null && ClassUtils.isAssignable(writeMethod.getParameterTypes()[0], readMethod.getReturnType())) {
try {
if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
readMethod.setAccessible(true);
}

Object value = readMethod.invoke(source);
if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
writeMethod.setAccessible(true);
}

writeMethod.invoke(target, value);
} catch (Throwable var15) {
throw new FatalBeanException("Could not copy property '" + targetPd.getName() + "' from source to target", var15);
}
}
}
}
}

}


推荐阅读

(点击标题可跳转阅读)

手把手实现一条延时消息

一文详细解读 Dubbo 中的 http 协议

Tomcat 在 SpringBoot 中是如何启动的


看完本文有收获?请转发分享给更多人

关注「ImportNew」,提升Java技能

好文章,我在看❤️

登录查看更多
0

相关内容

【2020新书】C++20 特性 第二版,A Problem-Solution Approach
专知会员服务
57+阅读 · 2020年4月26日
【模型泛化教程】标签平滑与Keras, TensorFlow,和深度学习
专知会员服务
20+阅读 · 2019年12月31日
【机器学习课程】Google机器学习速成课程
专知会员服务
162+阅读 · 2019年12月2日
【课程推荐】 深度学习中的几何(Geometry of Deep Learning)
专知会员服务
55+阅读 · 2019年11月10日
一个牛逼的 Python 调试工具
机器学习算法与Python学习
15+阅读 · 2019年4月30日
已删除
架构文摘
3+阅读 · 2019年4月17日
iOS自定义带动画效果的模态框
CocoaChina
7+阅读 · 2019年3月3日
C# 10分钟完成百度人脸识别
DotNet
3+阅读 · 2019年2月17日
Stata绘图:简单好用的37条外部命令
R语言中文社区
25+阅读 · 2018年9月22日
递归神经网络
Datartisan数据工匠
4+阅读 · 2018年8月2日
在Python中使用SpaCy进行文本分类
专知
24+阅读 · 2018年5月8日
为什么你应该学 Python ?
计算机与网络安全
4+阅读 · 2018年3月24日
用神经网络训练一个文本分类器
Python开发者
3+阅读 · 2017年8月19日
Arxiv
24+阅读 · 2020年3月11日
Revealing the Dark Secrets of BERT
Arxiv
4+阅读 · 2019年9月11日
Arxiv
21+阅读 · 2019年8月21日
Arxiv
19+阅读 · 2018年10月25日
Arxiv
26+阅读 · 2018年9月21日
Arxiv
4+阅读 · 2017年11月14日
VIP会员
相关资讯
一个牛逼的 Python 调试工具
机器学习算法与Python学习
15+阅读 · 2019年4月30日
已删除
架构文摘
3+阅读 · 2019年4月17日
iOS自定义带动画效果的模态框
CocoaChina
7+阅读 · 2019年3月3日
C# 10分钟完成百度人脸识别
DotNet
3+阅读 · 2019年2月17日
Stata绘图:简单好用的37条外部命令
R语言中文社区
25+阅读 · 2018年9月22日
递归神经网络
Datartisan数据工匠
4+阅读 · 2018年8月2日
在Python中使用SpaCy进行文本分类
专知
24+阅读 · 2018年5月8日
为什么你应该学 Python ?
计算机与网络安全
4+阅读 · 2018年3月24日
用神经网络训练一个文本分类器
Python开发者
3+阅读 · 2017年8月19日
相关论文
Arxiv
24+阅读 · 2020年3月11日
Revealing the Dark Secrets of BERT
Arxiv
4+阅读 · 2019年9月11日
Arxiv
21+阅读 · 2019年8月21日
Arxiv
19+阅读 · 2018年10月25日
Arxiv
26+阅读 · 2018年9月21日
Arxiv
4+阅读 · 2017年11月14日
Top
微信扫码咨询专知VIP会员