BeanUtils初步学习了解
偶然在工作项目中看到并对简单学习做个记录,欢迎各位大神指导!
在Java中BeanUtils出处共有两个地方,这个方法在不同的包下面,而这两个类的copyProperties()方法里面传递的参数赋值是相反的。例:BeanUtils.copyProperties(obja, objb);
其中:
在org.springframework.beans.BeanUtils包下的BeanUtils
个人在项目中使用的方法源码及注解为:
/**
* Copy the property values of the given source bean into the given target bean,
* ignoring the given "ignoreProperties".
* <p>Note: The source and target classes do not have to match or even be derived
* from each other, as long as the properties match. Any bean properties that the
* source bean exposes but the target bean does not will silently be ignored.
* <p>This is just a convenience method. For more complex transfer needs,
* consider using a full BeanWrapper.
* @param source the source bean
* @param target the target bean
* @param ignoreProperties array of property names to ignore
* @throws BeansException if the copying failed
* @see BeanWrapper
*/
//将给定源bean的属性值复制到给定的目标bean中,忽略给定的“ignoreProperties”。
//注意:只要属性匹配,源类和目标类不必匹配,甚至不必从彼此派生。
//源bean公开但目标bean没有公开的任何bean属性都将被忽略。这只是一种方便的方法。
//对于更复杂的传输需求,可以考虑使用完整的BeanWrapper。
public static void copyProperties(Object source, Object target, String... ignoreProperties) throws BeansException {
copyProperties(source, target, null, ignoreProperties);
}
为便于记忆可以理解为obja拷贝到objb,如果需要update则不需要注意是否忽略id,version等唯一性字段,若需要insert则要注意忽略唯一性字段,并将字段存储在String[]数组中作为方法的参数。
在org.apache.commons.beanutils.BeanUtils包下的BeanUtils
相应源码及注释:
/**
* <p>Copy property values from the origin bean to the destination bean
* for all cases where the property names are the same.</p>
* 对于属性名相同的所有情况,将属性值从源bean复制到目标bean。
* <p>For more details see <code>BeanUtilsBean</code>.</p>
*
* @param dest Destination bean whose properties are modified
* 属性被修改的目标bean
* @param orig Origin bean whose properties are retrieved
* 其属性被检索的原始源bean
*
* @throws IllegalAccessException if the caller does not have
* access to the property accessor method
* @throws IllegalArgumentException if the <code>dest</code> or
* <code>orig</code> argument is null or if the <code>dest</code>
* property type is different from the source type and the relevant
* converter has not been registered.
* @throws InvocationTargetException if the property accessor method
* throws an exception
* @see BeanUtilsBean#copyProperties
*/
public static void copyProperties(final Object dest, final Object orig)
throws IllegalAccessException, InvocationTargetException {
BeanUtilsBean.getInstance().copyProperties(dest, orig);
}
为便于记忆可以理解为objb拷贝到obja。(没用过就简单看了看源码。。。)
引用包出处不一样,意思就不一样,使用的时候一定要看清楚是哪个包下面的。
使用工具类后效率也会有影响,毕竟只是少写了代码,并没有少运行代码,而且最终还是有set操作。