如何使用springframework BeanUtils copyProperties忽略空值? [英] How to ignore null values using springframework BeanUtils copyProperties?

查看:235
本文介绍了如何使用springframework BeanUtils copyProperties忽略空值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何使用Spring Framework将属性从对象源复制到对象目的地,而忽略空值.

I would like to know how to copy the properties from an Object Source to an Object Dest ignoring null values​​ using Spring Framework.

我实际上使用带有此代码的Apache beanutils

I actually use Apache beanutils, with this code

    beanUtils.setExcludeNulls(true);
    beanUtils.copyProperties(dest, source);

做到这一点.但是现在我需要使用Spring.

to do it. But now i need to use Spring.

有帮助吗?

非常感谢

推荐答案

您可以创建自己的方法来复制属性,而忽略空值.

You can create your own method to copy properties while ignoring null values.

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

// then use Spring BeanUtils to copy and ignore null using our function
public static void myCopyProperties(Object src, Object target) {
    BeanUtils.copyProperties(src, target, getNullPropertyNames(src));
}

这篇关于如何使用springframework BeanUtils copyProperties忽略空值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆