`
happyqing
  • 浏览: 3151796 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

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

阅读更多

 

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

 

spring: 3.2.12,其他几个copyProperties方法最终都是调用的这个,

spring的比apache的的多一个带ignoreProperties的

private static void copyProperties(Object source, Object target, Class<?> editable, String... ignoreProperties)
		throws BeansException {

	Assert.notNull(source, "Source must not be null");
	Assert.notNull(target, "Target must not be null");

	Class<?> actualEditable = target.getClass();
	if (editable != null) {
		if (!editable.isInstance(target)) {
			throw new IllegalArgumentException("Target class [" + target.getClass().getName() +
					"] not assignable to Editable class [" + editable.getName() + "]");
		}
		actualEditable = editable;
	}
	PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);
	List<String> ignoreList = (ignoreProperties != null) ? Arrays.asList(ignoreProperties) : null;

	for (PropertyDescriptor targetPd : targetPds) {
		Method writeMethod = targetPd.getWriteMethod();
		if (writeMethod != null && (ignoreProperties == null || (!ignoreList.contains(targetPd.getName())))) {
			PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
			if (sourcePd != null) {
				Method readMethod = sourcePd.getReadMethod();
				if (readMethod != null &&
						ClassUtils.isAssignable(writeMethod.getParameterTypes()[0], readMethod.getReturnType())) {
					try {
						if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
							readMethod.setAccessible(true);
						}
						Object value = readMethod.invoke(source);
						if(value != null){	//只拷贝不为null的属性 by zhao
							if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
								writeMethod.setAccessible(true);
							}
							writeMethod.invoke(target, value);
						}
					}
					catch (Throwable ex) {
						throw new FatalBeanException(
								"Could not copy property '" + targetPd.getName() + "' from source to target", ex);
					}
				}
			}
		}
	}
}

 关键代码就是加一个判断

                        if(value != null){  //只拷贝不为null的属性 by zhao   
                            if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {   
                                writeMethod.setAccessible(true);   
                            }   
                            writeMethod.invoke(target, value);   
                        }

 

参考:http://simen-net.iteye.com/blog/644801

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics