前言
在 Java 项目开发中,不同层(DTO、VO、Entity)之间经常需要进行属性转换。BeanUtils.copyProperties
是 Spring 提供的用于快速实现对象属性复制的方法,本文将全面讲解它的使用方式、注意事项和拓展技巧。
一、基本使用方式
UserDTO dto = new UserDTO();
dto.setName("张三");
dto.setEmail("zhangsan@example.com");
UserEntity entity = new UserEntity();
BeanUtils.copyProperties(dto, entity);
默认会复制名称和类型相同的字段。
二、忽略特定字段
BeanUtils.copyProperties(dto, entity, "id", "createTime");
适用于需要过滤敏感字段(如主键、时间戳)场景。
三、常见应用场景
-
Controller 中将入参 DTO 转换为 Entity
-
Entity 转换为返回前端的 VO
-
Service 层中多个对象结构间的数据同步
四、注意事项
-
字段名称必须一致,类型兼容
-
不支持嵌套对象递归复制
-
基于反射实现,大量复制可能影响性能
五、只复制非空字段(Apache Commons BeanUtils)
BeanUtilsBean notNull = new BeanUtilsBean() {
@Override
public void copyProperty(Object dest, String name, Object value)
throws IllegalAccessException, InvocationTargetException {
if (value != null) {
super.copyProperty(dest, name, value);
}
}
};
notNull.copyProperties(target, source);
六、封装通用工具方法
public class BeanCopyUtil {
public static <S, T> T copy(S source, Supplier<T> targetSupplier, String... ignoreProperties) {
T target = targetSupplier.get();
BeanUtils.copyProperties(source, target, ignoreProperties);
return target;
}
}
调用示例:
UserEntity entity = BeanCopyUtil.copy(dto, UserEntity::new, "id");
七、拓展:MapStruct 替代方案
@Mapper(componentModel = "spring")
public interface UserMapper {
@Mapping(target = "id", ignore = true)
UserEntity toEntity(UserDTO dto);
}
适用于字段名称不一致、复杂转换逻辑、高性能场景。
八、总结
-
BeanUtils.copyProperties
是轻量级对象属性复制工具,适合快速开发 -
对于更复杂的属性映射,推荐使用 MapStruct 等工具
-
可通过封装工具类或扩展实现过滤空值、批量处理等功能
熟练掌握 BeanUtils
的使用,将显著提高 Java 开发效率,是日常开发中的实用利器之一。