Java中BeanUtils.copyProperties的11个坑总结

 更新时间:2023年05月29日 09:25:35   作者:捡田螺的小男孩  
我们日常开发中,经常涉及到DO、DTO、VO对象属性拷贝赋值,很容易想到org.springframework.beans.BeanUtils的copyProperties,它会自动通过反射机制获取源对象和目标对象的属性,pyProperties,会有好几个坑呢,本文将给大家总结一下遇到的坑,需要的朋友可以参考下

第1个坑: 类型不匹配

@Data
public class SourceBean {
    private Long age;
}
@Data
public class TargetBean {
    private String age;
}
public class Test {
    public static void main(String[] args) {
        SourceBean source = new SourceBean();
        source.setAge(25L);
        TargetBean target = new TargetBean();
        BeanUtils.copyProperties(source, target);
        System.out.println(target.getAge());  //拷贝赋值失败,输出null
    }
}

在上述demo中,源对象SourceBeanage属性是一个Long类型,而目标对象TargetBeanage属性是一个String类型。由于类型不匹配,BeanUtils.copyProperties不会赋值成功的。我跑demo的结果,控制台输出null

第2个坑: BeanUtils.copyProperties是浅拷贝

先给大家复习一下,什么是深拷贝?什么是浅拷贝?

  • 浅拷贝是指创建一个新对象,该对象的属性值与原始对象相同,但对于引用类型的属性,仍然共享相同的引用。换句话说,浅拷贝只复制对象及其引用,而不复制引用指向的对象本身。
  • 深拷贝是指创建一个新对象,该对象的属性值与原始对象相同,包括引用类型的属性。深拷贝会递归复制引用对象,创建全新的对象,以确保拷贝后的对象与原始对象完全独立

我再给个代码demo给大家看看哈:

public class Address {
    private String city;
    //getter 和 setter 方法省略
}
public class Person {
    private String name;
    private Address address;
    //getter 和 setter 方法省略
}
 Person sourcePerson = new Person();
 sourcePerson.setName("John");
 Address address = new Address();
 address.setCity("New York");
 sourcePerson.setAddress(address);
 Person targetPerson = new Person();
 BeanUtils.copyProperties(sourcePerson, targetPerson);
 sourcePerson.getAddress().setCity("London");
 System.out.println(targetPerson.getAddress().getCity());  // 输出为 "London"

在上述示例中,源对象Person的属性address是一个引用类型。当使用BeanUtils.copyProperties方法进行属性复制时,实际上只复制了引用,即目标对象targetPersonaddress 属性引用和源对象 sourcePersonaddress 属性引用指向同一个对象。因此,当修改源对象的address对象时,目标对象的address对象也会被修改。

大家日常开发中,要注意这个坑哈~

第3个坑:属性名称不一致

 public class SourceBean {
    private String username;
    // getter 和 setter 方法省略
}
public class TargetBean {
    private String userName;
    // getter 和 setter 方法省略
}
 SourceBean source = new SourceBean();
 source.setUsername("捡田螺的小男孩");
 TargetBean target = new TargetBean();
 BeanUtils.copyProperties(source, target);
 System.out.println(target.getUserName());   // 输出为 null

在上述示例中,源对象SourceBean 的属性名称是username,而目标对象TargetBean的属性名称也是userName但是,两个 username,一个N是大写,一个n是小写,即属性名称不一致BeanUtils.copyProperties方法无法自动映射这些属性(无法忽略大小写自动匹配),因此目标对象的userName属性值为null

大家日常开发中,要注意这个坑哈~ 比如大小写不一致,差一两个字母等等

第4个坑:Null 值覆盖

@Data
public class SourceBean {
    private String name;
    private String address;
}
@Data
public class TargetBean {
    private String name;
    private String address;
}
SourceBean source = new SourceBean();
source.setName("John");
source.setAddress(null);
TargetBean target = new TargetBean();
target.setAddress("田螺address");
BeanUtils.copyProperties(source, target);
System.out.println(target.getAddress());  // 输出为 null

在上述示例中,源对象 SourceBean 的 address 属性值为 null。默认情况下,BeanUtils.copyProperties 方法会将源对象中的 null 值属性覆盖到目标对象中。因此,目标对象的 address 属性值也为 null。

如果你不希望 null 值覆盖目标对象中的属性,可以使用 BeanUtils.copyProperties 方法的重载方法,并传入一个自定义的 ConvertUtilsBean 实例来进行配置。

第5个坑:注意引入的包

BeanUtils.copyProperties其实有两个包,分别是spring、apache。大家注意一下哈,这两个包,是有点不一样的:

//org.springframework.beans.BeanUtils(源对象在左边,目标对象在右边)
public static void copyProperties(Object source, Object target) throws BeansException 
//org.apache.commons.beanutils.BeanUtils(源对象在右边,目标对象在左边)
public static void copyProperties(Object dest, Object orig) throws IllegalAccessException, InvocationTargetException

大家使用的时候,要注意一下哈,千万注意自己引入的哪个BeanUtils,写对应参数位置。

第6个坑:Boolean类型数据+is属性开头的坑

SourceBean和TargetBean中的都有个属性isTianLuo,它们的数据类型保持不变,但是一个为基本类型boolean,一个为包装类型Boolean

@Data
public class SourceBean {
    private boolean isTianLuo;
}
@Data
public class TargetBean {
    private Boolean isTianLuo;
}

跑测试用里的时候,发现赋值不上:

SourceBean source = new SourceBean();
source.setTianLuo(true);
TargetBean target = new TargetBean();
BeanUtils.copyProperties(source, target);
System.out.println(target.getIsTianLuo()); // 输出为 null

为什么呢?即使是一个包装类型,一个基本类型,应该可以赋值上才对的。

这是因为当属性类型为boolean时,属性名以is开头,属性名会去掉前面的is,因此源对象和目标对象属性对不上啦。

大家使用BeanUtils.copyProperties过程中,要注意哈~

第7个坑:查找不到字段引用

在某些开发场景呢,如果我们要修改某个字段的赋值,我们可能会全文搜索它的所有set方法,看哪些地方引用到。

但是呢,如果使用BeanUtils.copyProperties就不知道是否引用到对应的ste方法啦即查找不到字段引用。这就可能导致你会漏掉修改对应的字段。

第8个坑:不同内部类,即使相同属性,也是赋值失败

@Data
public class CopySource {
    public String outerName;
    public CopySource.InnerClass innerClass;
    @Data
    public static class InnerClass {
        public String InnerName;
    }
}
@Data
public class CopyTarget {
    public String outerName;
    public CopyTarget.InnerClass innerClass;
    @Data
   public static class InnerClass {
        public String InnerName;
    }
}
CopySource test1 = new CopySource();
test1.outerName = "outTianluo";
CopySource.InnerClass innerClass = new CopySource.InnerClass();
innerClass.InnerName = "innerTianLuo";
test1.innerClass = innerClass;
System.out.println(test1);
CopyTarget test2 = new CopyTarget();
BeanUtils.copyProperties(test1, test2);
System.out.println(test2);  //输出CopyTarget(outerName=outTianluo, innerClass=null)

以上demo中,CopySourceCopyTarget各自存在一个内部类InnerClass,虽然这个内部类属性也相同,类名也相同,但是在不同的类中,因此Spring会认为属性不同,不会Copy;

如果要复制成功,可以让他们指向同一个内部类。

第9个坑:bean对应的属性,没有getter和setter方法,赋值失败

BeanUtils.copyProperties要拷贝属性值成功,需要对应的bean要有getter和setter方法。因为它是用反射拿到set和get方法再去拿属性值和设置属性值的。

@Data
public class SourceBean {
    private String value;
}
@Getter   //没有对应的setter方法
public class TargetBean {
    private String value;
}
SourceBean source = new SourceBean();
source.setValue("捡田螺的小男孩");
TargetBean target = new TargetBean();
BeanUtils.copyProperties(source, target);
System.out.println(target.getValue()); //输出null 

第10个坑:BeanUtils.copyProperties + 泛型

如果BeanUtils.copyProperties遇到泛型,也是很可能赋值失败的哈。大家看下这个例子:

@Data
public class CopySource {
    public String outerName;
    public List<CopySource.InnerClass> clazz;
    @Data
    public static class InnerClass {
        public String InnerName;
    }
}
@ToString
@Data
public class CopyTarget {
    public String outerName;
    public List<CopyTarget.InnerClass> clazz;
    @Data
    public static class InnerClass {
        public String InnerName;
    }
}
CopySource test1 = new CopySource();
test1.outerName = "outTianluo";
CopySource.InnerClass innerClass = new CopySource.InnerClass();
innerClass.InnerName = "innerTianLuo";
List<CopySource.InnerClass> clazz = new ArrayList<>();
clazz.add(innerClass);
test1.setClazz(clazz);
System.out.println(test1);
CopyTarget test2 = new CopyTarget();
BeanUtils.copyProperties(test1, test2);
System.out.println(test2);  //输出CopyTarget(outerName=outTianluo, clazz=null)

这里面的例子,BeanUtils.copyProperties方法拷贝包含泛型属性的对象clazzCopyTargetCopySource的泛型属性类型不匹配,因此拷贝赋值失败。

如果是低版本的包,泛型如果不匹配,则会报错,高本版则知识拷贝赋值失败。

第11个坑:性能问题

由于这些BeanUtils类都是采用反射机制实现的,对程序的效率也会有影响。我跑了个demo对比:

SourceBean sourceBean = new SourceBean();
sourceBean.setName("tianLuoBoy");
TargetBean target = new TargetBean();
long beginTime = System.currentTimeMillis();
for (int i = 0; i < 100000; i++) {  //循环10万次
      target.setName(sourceBean.getName());
}
System.out.println("common setter time:" + (System.currentTimeMillis() - beginTime));
long beginTime1 = System.currentTimeMillis();
for (int i = 0; i < 100000; i++) {  //循环10万次
    BeanUtils.copyProperties(sourceBean, target);
}
System.out.println("bean copy time:" + (System.currentTimeMillis() - beginTime1));
//输出
common setter time:3
bean copy time:331

可以发现,简单的setterBeanUtils.copyProperties对比,性能差距非常大。因此,慎用BeanUtils.copyProperties!!!

12. 替换BeanUtils.copyProperties的方案

以上聊了BeanUtils.copyProperties的11个坑,都是在跟大家聊,要慎用BeanUtils.copyProperties。那有没有推荐替换它的方案呢。

第一种,那就是使用原始的setter和getter方法。

使用手动的setter方法进行属性赋值。这种方法可能需要编写更多的代码,但是可以提供更细粒度的控制,并且在性能方面通常比BeanUtils.copyProperties更高效。

Target target = new Target();
target.setName(source.getName());
target.setAge(source.getAge());

如果实在对象bean的属性比较多的话,可以使用插件GenerateAllSetter,它可以一键生成对象的set方法,挺方便的。

第二种方案,使用映射工具库,如MapStruct、ModelMapper等,它们可以自动生成属性映射的代码。这些工具库可以减少手动编写setter方法的工作量,并提供更好的性能。

使用MapStruct的示例:

@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);

以上就是Java中BeanUtils.copyProperties容易遇到的11个坑总结的详细内容,更多关于Java BeanUtils.copyProperties坑的资料请关注脚本之家其它相关文章!

相关文章

  • java代码关闭tomcat程序及出现问题解析

    java代码关闭tomcat程序及出现问题解析

    这篇文章主要介绍了java代码关闭tomcat程序 及出现问题解析,本文通过实例代码给大家介绍的非常详细,需要的朋友可以参考下
    2019-05-05
  • 使用Maven进行依赖排除的详细步骤

    使用Maven进行依赖排除的详细步骤

    在Maven中,依赖排除是一种常见的技术,用于从项目的依赖中排除特定的传递性依赖,这通常用于解决依赖冲突或避免引入不需要的库,以下是如何在Maven中使用依赖排除的详细步骤,包括代码示例,需要的朋友可以参考下
    2024-11-11
  • 详解SpringCloud Ribbon 负载均衡通过服务器名无法连接的神坑

    详解SpringCloud Ribbon 负载均衡通过服务器名无法连接的神坑

    这篇文章主要介绍了详解SpringCloud Ribbon 负载均衡通过服务器名无法连接的神坑,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2019-06-06
  • SpringBoot文件上传接口并发性能调优

    SpringBoot文件上传接口并发性能调优

    在一个项目现场,文件上传接口(文件500K)QPS只有30,这个并发性能确实堪忧,此文记录出坑过程,文中通过代码示例讲解的非常详细,具有一定的参考价值,需要的朋友可以参考下
    2024-06-06
  • 详解Java中对象序列化与反序列化

    详解Java中对象序列化与反序列化

    这篇文章主要为大家详细介绍了Java中对象序列化与反序列化,感兴趣的小伙伴们可以参考一下
    2016-02-02
  • Java缩小文件内存占用的方法技巧分享

    Java缩小文件内存占用的方法技巧分享

    在Java应用程序中,处理大文件时经常会遇到内存占用过高的问题,为了缩小文件的内存占用,我们可以采取一些有效的方法来优化和管理内存的使用,本文将介绍一些在Java中缩小文件内存占用的技巧,需要的朋友可以参考下
    2024-10-10
  • SpringBoot获取resources目录下的文件

    SpringBoot获取resources目录下的文件

    在 Spring Boot 项目中,获取 resources 目录中的文件路径通常涉及到访问类路径资源,Spring Boot 提供了一些工具类和方法,下面小编就来和大家详细聊聊
    2024-10-10
  • MyBatis一对一级联更新问题小结

    MyBatis一对一级联更新问题小结

    日常工作中经常会涉及到一对一级联更新的问题,本文主要介绍了MyBatis一对一级联更新问题小结,具有一定的参考价值,感兴趣的可以了解一下
    2024-01-01
  • Java8新特性之再见Permgen_动力节点Java学院整理

    Java8新特性之再见Permgen_动力节点Java学院整理

    这篇文章主要介绍了Java8新特性之再见Permgen的相关知识,非常不错,具有参考借鉴价值,需要的的朋友参考下吧
    2017-06-06
  • Java实现一个简单的定时器代码解析

    Java实现一个简单的定时器代码解析

    这篇文章主要介绍了Java实现一个简单的定时器代码解析,具有一定借鉴价值,需要的朋友可以参考下。
    2017-12-12

最新评论