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覆蓋

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM