1.前言
我们时常会遇到需要拷贝bean的情况,如返回vo时,需要隐藏一些敏感的字段,来实现系统的安全性。我们常用copyProperties方法,但copyProperties无法拷贝集合,所以我封装了一个工具类来实现集合的拷贝
2.工具类
利用org.springframework.beans.BeanUtils包的copyProperties方法
采用泛型、stream流,来实现单个bean和集合的拷贝。
代码如下:
public class BeanCopyUtils {
private BeanCopyUtils(){
}
//单个实体类拷贝
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;
}
public static <O,V> List<V> copyBeanList(List<O> list,Class<V> clazz){
List<V> result = list.stream()
.map(o -> copyBean(o, clazz))
.collect(Collectors.toList());
return result;
}
}
3.具体实践
我有两个实体类,一个user,一个userVo。其中userVo中没有密码字段,用来返回给前端。
public class User implements Serializable {
/**
* 主键
*/
@TableId
private Integer id;
/**
* 姓名
*/
private String name;
/**
* 密码
*/
private String password;
@TableField(exist = false)
private static final long serialVersionUID = 1L;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserVo implements Serializable {
/**
* 主键
*/
private Integer id;
/**
* 姓名
*/
private String name;
}
单个bean拷贝
@Test
public void testBeanCopy(){
User user = new User();
user.setId(1);
user.setName("张三");
user.setPassword("123456");
System.out.println(user);
UserVo userVo = BeanCopyUtils.copyBean(user, UserVo.class);
System.out.println(userVo);
}
User(id=1, name=张三, password=123456)
UserVo(id=1, name=张三)
集合bean拷贝
@Test
public void testBeanListCopy(){
//调用mp的selectList方法来查询全部用户
List<User> userList = userMapper.selectList(null);
System.out.println(userList);
List<UserVo> userVos = BeanCopyUtils.copyBeanList(userList, UserVo.class);
System.out.println(userVos);
}
[User(id=1, name=张三, password=123456), User(id=2, name=李四, password=123456), User(id=3, name=王五, password=123456), User(id=4, name=赵六, password=123456)]
[UserVo(id=1, name=张三), UserVo(id=2, name=李四), UserVo(id=3, name=王五), UserVo(id=4, name=赵六)]