BeanUtils.copyProperties使用分析

概述

在开发中,常使用 BeanUtils.copyProperties() 进行PO,VO,DTO等对象的复制和转换

注意

使用 Spring 的 BeanUtils # CopyProperties 方法去拷贝对象属性时需要对应的属性有 getter 和 setter 方法(内部实现时,使用反射拿到 set 和 get 方法,再去获取/设置属性值);

如果存在属性完全相同得内部类,但不是同一个内部类(即分别属于各自得内部类),则 Spring 会认为属性不同,不会Copy
泛型只在编译期起作用,不能依靠泛型来做运行期的限制;

Spring 和 Apache 的 copy 属性得方法源和目的参数得位置正好相反,所以导包和调用得时候需要注意

在进行属性拷贝时,低版本的 Apache CommonsBeanUtils 为了解决 Date 为空的问题,会导致为目标对象的原始类型的包装类属性赋予初始值如 Integer 属性默认赋值为 0,尽管你的来源对象该字段的值为 null

优点

简化代码

如果不使用改方法的话,将一个对象里面的数据复制到另一个对象,便会导致有很多get和set方法,让代码看着非常臃肿

缺点

缺点是使用 BeanUtils 的成本惊人地昂贵!BeanUtils 所花费的时间要超过取数据、将其复制到对应的 destObject 对象(通过手动调用 get 和 set 方法),以及通过串行化将其返回到远程的客户机的时间总和

Spring 和 Apache 的 copyProperties区别

两者参数顺序不一样,在使用时一定要注意这个区别

org.springframework.beans.BeanUtils

源码如下

// Spring 将源对象中的值拷贝到目标对象 
// 注意,目标对象在后。
public static void copyProperties(Object source, Object target) throws BeansException {
   
    
    
   copyProperties(source, target, (Class)null, (String[])null);
}

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 !&

猜你喜欢

转载自blog.csdn.net/yyuggjggg/article/details/133986389