【问题标题】:Ignore null values in BeanUtils.copyProperties忽略 BeanUtils.copyProperties 中的空值
【发布时间】:2017-10-03 15:03:41
【问题描述】:

我正在使用 Apache Commons BeanUtils 将一些属性从源 Bean 复制到目标 Bean。在此,我不想在来自源 bean 的目标 bean 中设置空值。

例如:

Person sourcePerson = new Person();
sourcePerson.setHomePhone("123");
sourcePerson.setOfficePhone(null);

Person destPerson = new Person();
destPerson.setOfficePhone("456");

BeanUtils.copyProperties(destPerson, sourcePerson);
System.out.println(destPerson.getOffcePhone());

//这里destPerson officePhone设置为null

如何避免这种情况?我什至尝试提出以下声明: BeanUtilsBean.getInstance().getConvertUtils().register(false, false, 0);

这似乎没有帮助。

我们可以在 Apache Commons BeanUtils 中排除空值吗?

【问题讨论】:

  • 您可以使用不会尝试转换属性的 PropertyUtils...否则您需要注册 ConvertUtils.register 以获得默认值...
  • 我不想要任何默认值,我只是不想用 null 覆盖现有值。我还是不明白 PropertyUtils 是如何排除空值的。
  • @StanislavL ignoreProperties 选项不能解决这个问题,ConvertUtils 也没有,如问题中所述。

标签: java spring mapping apache-commons-beanutils


【解决方案1】:

Apache Commons BeanUtils 不支持这种情况。所以你应该自己做:

public class BeanUtils {

    public static void copyPropertiesIgnoreNull(Object source, Object dest) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();
        for(java.beans.PropertyDescriptor pd : pds) {
            if(!src.isReadableProperty(pd.getName()) || pd.getWriteMethod() == null){
                continue;
            }
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null) {
                continue;
            }
            BeanUtils.copyProperties(dest, pd.getName(), srcValue);
        }
    }
}

【讨论】:

  • 您使用哪个软件包/版本来使其工作? BeanUtils.copyProperties(dest, pd.getName(), srcValue);
【解决方案2】:

当嵌套属性时,BeanUtils 不起作用,例如 contact.businessName.firstname 其中 firstName 是字符串,其他是用户定义的类。

【讨论】:

    【解决方案3】:

    扩展 BeanUtilsBean

    public class NullAwareBeanUtilsBean extends BeanUtilsBean{
      @Override
      public void copyProperty(Object dest, String name, Object value)
          throws IllegalAccessException, InvocationTargetException {
        if(value==null)return;
        super.copyProperty(dest, name, value);
      }
    }
    
    BeanUtilsBean notNull = new NullAwareBeanUtilsBean();
    notNull.copyProperties(target, source);
    

    应该可以的。

    【讨论】:

      猜你喜欢
      • 2014-03-27
      • 2019-02-27
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      • 2019-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多