Java 实用工具类:深入使用 BeanUtils.copyProperties

前言

        在 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 层中多个对象结构间的数据同步


四、注意事项

  1. 字段名称必须一致,类型兼容

  2. 不支持嵌套对象递归复制

  3. 基于反射实现,大量复制可能影响性能


五、只复制非空字段(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 开发效率,是日常开发中的实用利器之一。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Stay Passion

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值