spring BeanUtils.copyProperties只拷贝不为null的属性

在MVC的开发模式中经常需要将model与pojo的数据绑定,apache和spring的工具包中都有BeanUtils,使用其中的copyProperties方法可以非常方便的进行这些工作,但在实际应用中发现,对于null的处理不太符合个人的需要,例如在进行修改操作中只需要对model中某一项进行修改,那么一般我们在页面上只提交model的ID及需要修改项的值,这个时候使用BeanUtils.copyProperties会将其他的null绑定到pojo中去。

BeanUtils.copyProperties的使用要导入:

org.springframework.beans.BeanUtils;
直接上代码:
package com.test;

import com.hourumiyue.system.SpringUtil;
import org.springframework.beans.BeanUtils;

public class TestBeanUtiles {

    public static void main(String[] args) {

        NewPerson newPerson = new NewPerson();
        newPerson.setName("miyue");//前台用户更新过的数据,例如前台只修改了用户名

        //下面我们假设是从数据库加载出来的老数据
        OldPerson oldPerson = new OldPerson();
        oldPerson.setSex("nv");
        oldPerson.setAge(5);
        //如果我们想把新数据更新到老数据这个对象里面,我们就可以借助BeanUtils.copyProperties()的方法如下:
        BeanUtils.copyProperties(newPerson, oldPerson);
     System.out.println(newPerson.toString());
        System.out.println(oldPerson.toString());
    }
}

上面的代码打印结果如下:

NewPerson{name='miyue', sex='null', age=0}
OldPerson{name='miyue', sex='null', age=0}

从上面我们可以看出,新的对象确实把修改的数据更新给老对象了,但是它却把原来为null或者int类型默认为0的值也都赋给了老对象,这肯定不合理的,下面我们自己写了一个加工类,大家可以直接调用我们加工类的copyPropertiesIgnoreNull()方法即可忽略null值,避免老数据被null覆盖的尴尬:

/**
 * 版权所有 (c) 2018,中金支付有限公司  
 */
package com.yanshemiyue.system;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.HashSet;
import java.util.Set;

/**
* 类说明
* 
* <pre>
* Modify Information:
* Author        Date          Description
* ============ =========== ============================
* houru      2018年1月4日    Create this file
* </pre>
* 
*/

public class SpringUtil implements ApplicationContextAware {

    /** 
     * 当前IOC 
     *  
     */  
    private static ApplicationContext applicationContext;  

    /** 
     * * 设置当前上下文环境,此方法由spring自动装配 
     *  
     */  
    @Override  
    public void setApplicationContext(ApplicationContext arg0)  
            throws BeansException {  
        applicationContext = arg0;  
    }  

    /** 
     * 从当前IOC获取bean 
     * 
     * @param id 
     * bean的id 
     * @return 
     *
     */  
    public static Object getObject(String id) {  
        Object object = null;  
        object = applicationContext.getBean(id);  
        return object;  
    } 
    
    public static String[] getNullPropertyNames (Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set<String> emptyNames = new HashSet<String>();
        for(java.beans.PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null) emptyNames.add(pd.getName());
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }

    public static void copyPropertiesIgnoreNull(Object src, Object target){
        BeanUtils.copyProperties(src, target, getNullPropertyNames(src));
    }

}

调用:copyPropertiesIgnoreNull

package com.test;
import com.yxjr.system.SpringUtil;
public class TestBeanUtiles {
    public static void main(String[] args) {
        NewPerson newPerson = new NewPerson();
        newPerson.setName("miyue");//前台用户更新过的数据,例如前台只修改了用户名
        //下面我们假设是从数据库加载出来的老数据
        OldPerson oldPerson = new OldPerson();
        oldPerson.setSex("nv");
        oldPerson.setAge(5);
        //如果我们想把新数据更新到老数据这个对象里面,我们就可以借助BeanUtils.copyProperties()的方法如下:
        //BeanUtils.copyProperties(newPerson, oldPerson);
        SpringUtil.copyPropertiesIgnoreNull(newPerson, oldPerson);
        System.out.println(newPerson.toString());
        System.out.println(oldPerson.toString());
    }
}

打印结果:

NewPerson{name='miyue', sex='null', age=0}
OldPerson{name='miyue', sex='nv', age=0}

现在就可以看出老数据没有被null覆盖

原文地址:https://www.cnblogs.com/luzhanshi/p/11129982.html