如何忽略空值使用springframework BeanUtils copyProperties? (解决了) [英] How to ignore null values using springframework BeanUtils copyProperties? (Solved)
本文介绍了如何忽略空值使用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.
任何帮助?
Thx很多
推荐答案
您可以创建自己的方法来复制属性,同时忽略空值。
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
public static void myCopyProperties(Object src, Object target) {
BeanUtils.copyProperties(src, target, getNullPropertyNames(src))
}
这篇关于如何忽略空值使用springframework BeanUtils copyProperties? (解决了)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文