Spring 提供的 BeanUtils 遇到的问题

BeanUtils 功能:这个包里比较常用的一个工具类,这里只介绍它的 copyProperties()方法。如果你有两个具有很多相同属性的JavaBean,怎可以通过该方法进行对象之间的赋值操作,如下:

/**
 * 对象属性拷贝 <br>
 * 将源对象的属性拷贝到目标对象
 *
 * @param source 源对象
 * @param target 目标对象
 */
public static void copyProperties(Object source, Object target) {
	try {
		BeanUtils.copyProperties(source, target);
	} catch (BeansException e) {
		LOGGER.error("BeanUtil property copy  failed :BeansException", e);
	} catch (Exception e) {
		LOGGER.error("BeanUtil property copy failed:Exception", e);
	}
}

问题及解决当 source 类中某些属性与 target 类中不同时,就会导致相同的类也不会赋值。这个真的很不爽,这时我们可以使用 hutool 包下的 BeanUtil 来实现。

BeanUtil.copyProperties(source,target);

问题及解决BeanUtils外还有一个名为PropertyUtils的工具类,它也提供copyProperties()方法,作用 与BeanUtils的同名方法十分相似,主要的区别在于后者提供类型转换功能,即发现两个JavaBean的同名属性为不同类型时,在支持的数据类型范围内进行转换,而前者不支持这个功能,但是速度会更快一些。

----架构师资料,关注公众号获取----

猜你喜欢

转载自blog.csdn.net/zhengzhaoyang122/article/details/105604344