public class MyBeanUtils
extends org.apache.commons.beanutils.BeanUtils {
public static void copyBeanNotNull2Bean(Object databean,Object tobean)throws Exception
{
PropertyDescriptor origDescriptors[] =
PropertyUtils.getPropertyDescriptors(databean);
for (int i = 0; i < origDescriptors.length; i++) {
String name = origDescriptors[i].getName();
// String type = origDescriptors[i].getPropertyType().toString();
if ("class".equals(name)) {
continue; // No point in trying to set an object's class
}
if (PropertyUtils.isReadable(databean, name) &&
PropertyUtils.isWriteable(tobean, name)) {
try {
Object value = PropertyUtils.getSimpleProperty(databean, name);
if(value!=null){
copyProperty(tobean, name, value);
}
}
catch (java.lang.IllegalArgumentException ie) {
logger.error(ie,ie); // Should not happen
}
catch (Exception e) {
logger.error(e,e); // Should not happen
}
}
}
}
}
使用这段代码进行javabean的复制,并且srcBean为null的字段,不进行复制。
这段代码测试环境是正常的,在生产环境下,运行一段时间后(大概有1个月的样子),就会出现很诡异的问题,javaBean里面Integer,Long等类型的 复制后字段变成null了(源javaBean和目标javaBean该字段都不不为空的情况下)。
正在持续监测中...
注:copyProperty 方法是继承于org.apache.commons.beanutils.BeanUtils
===================================================================
2014/04/27
问题终于解决了!
原因是项目引用的另一个第三方jar包里,对BeanUtils注册了全局的转换器
ConvertUtils.register(new xxx.DateConverter(), Date.class);
ConvertUtils.register(new xxx.BigDecimalConverter(), BigDecimal.class);
ConvertUtils.register(new xxx.IntegerConverter(), Integer.class);
而这三个转换器里面因为某种原因,存在这样的逻辑:
即srcBean和targetBean中类型相同的字段,返回null
这个第三方jar也使用了apache beanUtils,不过用途并不是复制bean,所以使用了这种逻辑的转换。
结果就是造成了我的项目中 一旦使用了这个第三方jar的功能之后,转换器被注册,之后便出现了文中开头的问题,也就是所谓的“运行一段时间后,便出现bean复制null的情况”。