0
点赞
收藏
分享

微信扫一扫

list循环赋值_优雅的使用BeanUtils对List集合的操作

摘要

我们在Entity、Bo、Vo层数据间可能经常转换数据,Entity对应的是持久层数据结构(一般是数据库表的映射模型)、Bo对应的是业务层操作的数据结构、Vo就是Controller和客户端交互的数据结构。在这些数据结构之间很大一部分属性都可能会相同,我们在使用的时候会不断的重新赋值。

如:客户端传输管理员信息的到Web层,我们会使用AdminVo接收,但是到了Service层时,我就需要使用AdminBo,这时候就需要把AdminVo实例的属性一个一个赋值到AdminBo实例中。

BeanUtils

Spring 提供了 org.springframework.beans.BeanUtils 类进行快速赋值,如:

AdminEntity类

public class AdminEntity{
private Integer id;

private String password;

private String username;

private String userImg;
.... //一些 Set Get方法
}


AdminVo类,因为是和客户端打交道的,所以password属性就不适合在这里了

public class AdminVo{
private Integer id;

private String username;

private String userImg;
.... //一些 Set Get方法
}


假如我们需要把AdminEntity实例属性值赋值到AdminVo实例中(暂时忽略Bo层吧)

AdminEntity entity = ...;
AdminVo vo = new AdminEntity();
// org.springframework.beans.BeanUtils
BeanUtils.copyProperties(entity, vo); // 赋值

  那么这样AdminVo实例中的属性值就和AdminEntity实例中的属性值一致了。

但是如果我们是一个集合的时候就不能这样直接赋值了。如:

List<Admin> adminList = ...;
List<AdminVo> adminVoList = new ArrayList<>(adminList.size());
BeanUtils.copyProperties(adminList, adminVoList); // 赋值失败

  这样直接赋值是不可取的,由方法名(copyProperties)可知,只会复制他们的属性值,那么上述的​​adminList​​​属性和​​adminVoList​​的属性是没有半毛钱关系的。那么怎么解决了?

(优雅、推荐)

这也是我第一次写泛型的代码,可能有待提高,如下:
ColaBeanUtils类(Cola是我家的狗狗名,哈哈)

import org.springframework.beans.BeanUtils;

public class ColaBeanUtils extends BeanUtils {

public static <S, T> List<T> copyListProperties(List<S> sources, Supplier<T> target) {
return copyListProperties(sources, target, null);
}

/**
* @author Johnson
* 使用场景:Entity、Bo、Vo层数据的复制,因为BeanUtils.copyProperties只能给目标对象的属性赋值,却不能在List集合下循环赋值,因此添加该方法
* 如:List<AdminEntity> 赋值到 List<AdminVo> ,List<AdminVo>中的 AdminVo 属性都会被赋予到值
* S: 数据源类 ,T: 目标类::new(eg: AdminVo::new)
*/
public static <S, T> List<T> copyListProperties(List<S> sources, Supplier<T> target, ColaBeanUtilsCallBack<S, T> callBack) {
List<T> list = new ArrayList<>(sources.size());
for (S source : sources) {
T t = target.get();
copyProperties(source, t);
if (callBack != null) {
// 回调
callBack.callBack(source, t);
}
list.add(t);
}
return list;
}


ColaBeanUtilsCallBack接口,使用java8的lambda表达式注解:

@FunctionalInterface
public interface ColaBeanUtilsCallBack<S, T> {

void callBack(S t, T s);
}


使用方式如下:

List<AdminEntity> adminList = ...;
List<ArticleVo> articleVoList = ColaBeanUtils.copyListProperties(adminList, AdminVo::new);
return articleVoList;


如果需要在循环中做处理(回调),那么可使用lambda表达式:

List<Article> adminEntityList = articleMapper.getAllArticle();
List<ArticleVo> articleVoList = ColaBeanUtils.copyListProperties(adminEntityList , ArticleVo::new, (articleEntity, articleVo) -> {
// 回调处理
});
return articleVoList;



举报

相关推荐

0 条评论