Spring之BeanUtils工具类简介说明
下文笔者讲述Spring中Bean工具类简介说明,如下所示
BeanUtils简介
BeanUtils是一个Java类库 用于简化Java Bean对象之间的属性拷贝和赋值操作
BeanUtils的基本用法
BeanUtils提供一组静态方法
可快速地实现Bean对象之间的属性复制、属性转换、属性赋值等操作
如:
copyProperties()方法
可将一个Bean对象的属性值复制到另一个Bean对象中
BeanUtils.copyProperties(destination, source);
destination和source都是Java Bean对象。
在使用BeanUtils进行属性复制时
会自动匹配两个Bean对象中相同名称的属性
并将源Bean对象中对应属性的值复制到目标Bean对象中
需要注意的是,两个Bean对象中的属性名称和类型必须要匹配,否则会抛出异常
================================================================================
BeanUtils还提供一些其他的方法
如:
getProperty()、setProperty()、populate()等等
可用于获取属性值、设置属性值、批量设置属性值等操作。
String value = BeanUtils.getProperty(bean, "propertyName");
BeanUtils.setProperty(bean, "propertyName", "value");
BeanUtils高级用法
自定义属性映射规则
BeanUtils默认使用相同名称的属性进行属性复制
如果需要自定义属性映射规则
可使用BeanUtils提供的自定义转换器
下面是一个自定义转换器的示例代码:
// 自定义转换器
class CustomConverter implements Converter {
public Object convert(Class type, Object value) {
// 自定义转换逻辑
return convertedValue;
}
}
// 使用自定义转换器进行属性复制
ConvertUtils.register(new CustomConverter(), String.class);
BeanUtils.copyProperties(destination, source);
2.2 批量设置属性值
BeanUtils提供populate()方法 可将Map中的属性值批量设置到Bean对象中例
Map<String, String> properties = new HashMap<>();
properties.put("propertyName1", "value1");
properties.put("propertyName2", "value2");
BeanUtils.populate(bean, properties);
3、BeanUtils注意事项
两个Bean对象中的属性名称和类型必须要匹配,否则会抛出异常 如果需要进行更加复杂的属性映射、类型转换等操作,可能需要使用其他的类库或工具 在使用BeanUtils时,需要引入commons-beanutils包和commons-logging包
根据BeanUtils(Spring包)封装的工具类
public class BaseConverter {
/**
* 对象属性赋值
* @param source 源对象
* @param clazz 目标类
* @param properties
* @param <K>
* @return
*/
public static <K> K convert(Object source, Class<K> clazz, String... properties) {
if (source == null) {
return null;
}
K target = (K) BeanUtils.Instantiate(clazz);
BeanUtils.copyProperties(source, target, properties);
return target;
}
/**
* list集合之间的对象属性赋值
* @param sourceList 输入集合
* @param clazz 输出集合类型
* @param properties
* @param <K> 输出集合类型
* @return 返回集合
*/
public static <K> List<K> convertList(List<?> sourceList, Class<K> clazz, String... properties) {
List<K> list = new ArrayList<K>();
if (null == sourceList || sourceList.size() < 1) {
return list;
}
for (Object source : sourceList) {
if (null == source) {
continue;
}
K target = convert(source, clazz, properties);
list.add(target);
}
return list;
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


