简单来讲,就是 把一个bean对象中的字段拷贝到另一个bean对象的字段
它在spring项目中常用来封装VO对象向前端传递数据。
例如:当前A对象有6个字段,而前端只需获取其中3个字段,我们则需将此3个字段封装(VO)返回前端,而不应将A中的6个字段(PO)返回前端。
但是我们每次都new 对象,然后get/set 赋值会很繁琐,代码复用性和效率不高,因此我们可以使用apche提供的BeanUtils工具类
package com.mae.vuedemo.beanutils;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @Author: Mae
* @Date: 2022/2/7
* @Time: 21:44
* @Description:
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Long id;
private String name;
private String password;
private String email;
private Integer sex;
}
package com.mae.vuedemo.beanutils;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @Author: Mae
* @Date: 2022/2/7
* @Time: 21:45
* @Description:
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserVo {
private String name;
private String email;
}
copyProperties(Object source, Object target):
将source中的字段添加到target中
注意:两对象中对应字段名和类型应完全相同,否则无法拷贝
public class Demo {
public static void main(String[] args) {
User user = getUser();
UserVo userVo = new UserVo();
System.out.println("拷贝前:");
System.out.println(userVo);
BeanUtils.copyProperties(user, userVo);
System.out.println("拷贝后:");
System.out.println(userVo);
}
private static User getUser() {
User user = new User(1L, "Mae", "555555", "[email protected]", 0);
return user;
}
}
拷贝前:
UserVo(name=null, email=null)
拷贝后:
UserVo(name=Mae, [email protected])
拷贝前:
[]
拷贝后
[UserVo(name=Mae, email=48488@mae.com), UserVo(name=Naomi, email=48488@mae.com), UserVo(name=Mae2, email=48488@mae.com), UserVo(name=Naomi, email=484dd88@mae.com)]
实际项目中,我们还需要对BeanUtils进一步封装,因为Bean拷贝我们经常用到每次都像上面那样的话代码非常冗余且无法复用,因此我们进一步封装BeanUtils,使得每一个PO类都能够实现Bean拷贝(前提字段相同)
前提知识对 反射、泛型、stream流 应用 比较熟练
public class BeanCopyUtils {
private BeanCopyUtils() {
}
/** 1、单个对象*/
public static <V> V copyBean(Object source, Class<V> clazz) {
/** 创建目标对象 实现属性拷贝*/
V result = null;
try {
result = clazz.newInstance();
/** 拷贝*/
BeanUtils.copyProperties(source, result);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/** 2、集合*/
public static <O, V> List<V> copyBeanList(List<O> list, Class<V> clazz) {
/** 创建目标对象 实现属性拷贝*/
return list.stream()
.map(o -> copyBean(o, clazz))
.collect(Collectors.toList());
}
}
User user = getUser();
UserVo userVo = BeanCopyUtils.copyBean(user, UserVo.class);
System.out.println(userVo);
List<User> users=getUserList();
List<UserVo> userVos = BeanCopyUtils.copyBeanList(users, UserVo.class);
System.out.println(userVos);
UserVo(name=Mae, [email protected])
[UserVo(name=Mae, [email protected]), UserVo(name=Naomi, [email protected]), UserVo(name=Mae2, [email protected]), UserVo(name=Naomi, [email protected])]