M4RKYU.SYSEdition 2027
Skip to content
LOCZH/安大略 · 加拿大/▸logs · advanced java simplifying object property copy and manipulation with beanutil 3l2n待机OK/--:--:--EST
M4M4RK_YUportfolio
  • 创作创作
    创作Overview
    • 作品精选案例与项目记录
    • 游戏可玩原型与游戏开发日志
  • 影像影像
    影像Overview
    • 照片影像合集与视觉实验
    • 商店印刷品、海报和限量物件
  • 写作写作
    写作Overview
    • 博客长篇开发日志与现场笔记
    • 笔记短观察、链接与代码片段
  • 资源资源
    资源Overview
    • 工具38 款浏览器内开发工具
    • 链接每日使用的开发与设计书签
  • 关于关于
  • 联系联系
EN

同步 · dev.to / @markyu

Java BeanUtils Copying: Convenient, but Not Free

A practical Java guide to BeanUtils, shallow copy pitfalls, reflection overhead, and when MapStruct or manual mapping is a better choice.

发布日期
May 26 '24
·
阅读时长
3 min read
·
点赞
12
·
评论数
2
javabackendperformancespring
在 dev.to 查看评论

本页目录

  • The Basic Copy
  • Shallow Copy Is the First Trap
  • Reflection Has a Cost
  • Spring BeanUtils vs Apache BeanUtils
  • A Safer DTO Mapping Example
  • Where BeanUtils Still Makes Sense
  • Production Pitfall: Copying Too Much
  • Final Thought

Bean copying looks harmless until it hides a production bug.

I have used BeanUtils.copyProperties() for DTO conversion because it is fast to write. Then later someone adds a nested object, a field name changes, or performance matters, and the convenient helper suddenly becomes a quiet source of confusion.

So here is the practical rule:

Use BeanUtils for simple, boring object copying. Do not use it as your default domain mapping strategy.

The Basic Copy

With Apache Commons BeanUtils:

import org.apache.commons.beanutils.BeanUtils;

public class CopyDemo {
    public static void main(String[] args) throws Exception {
        UserEntity entity = new UserEntity("Mark", 30);
        UserDTO dto = new UserDTO();

        BeanUtils.copyProperties(dto, entity);

        System.out.println(dto);
    }
}

That is the reason people like it. One line replaces a bunch of setters.

But the hidden question is:

What exactly did it copy?

Shallow Copy Is the First Trap

If the object contains nested objects, BeanUtils copies the reference. It does not magically deep-copy your object graph.

class UserEntity {
    private String name;
    private Address address;
}

class UserDTO {
    private String name;
    private Address address;
}

After copying, both objects can point at the same Address.

That may be fine. It may also be a bug if one layer mutates the nested object.

Visual map:

UserEntity.address ----+
                       +----> same Address object
UserDTO.address -------+

If you need independent nested objects, write that mapping explicitly or use a mapper designed for it.

Reflection Has a Cost

BeanUtils usually relies on reflection and runtime property inspection.

That means:

  • less compile-time safety
  • slower mapping than direct code
  • mistakes may show up later
  • refactoring fields can be riskier

For one admin endpoint, who cares.

For mapping thousands of rows in a hot path, I would care.

Spring BeanUtils vs Apache BeanUtils

The method names look similar, but behavior differs.

ToolGood forWatch out
Spring BeanUtilssimple same-name copylimited conversion
Apache BeanUtilsstring conversion and dynamic property accessreflection overhead
MapStructproduction DTO mappingsetup and annotations
Manual mappingcritical domain logicmore code

My current preference:

  • quick internal tools: BeanUtils
  • API DTO mapping: MapStruct or manual mapping
  • sensitive business logic: manual mapping

A Safer DTO Mapping Example

Sometimes boring explicit code is better:

public UserDTO toDto(UserEntity entity) {
    UserDTO dto = new UserDTO();
    dto.setName(entity.getName());
    dto.setAge(entity.getAge());

    if (entity.getAddress() != null) {
        AddressDTO address = new AddressDTO();
        address.setCity(entity.getAddress().getCity());
        address.setCountry(entity.getAddress().getCountry());
        dto.setAddress(address);
    }

    return dto;
}

Yes, it is longer.

But during a code review, nobody has to guess what happens to address.

Where BeanUtils Still Makes Sense

I would still use it for:

  • small admin tools
  • test fixtures
  • simple JavaBean-to-JavaBean copying
  • prototypes
  • non-critical internal scripts

I would avoid it for:

  • hot paths
  • payment/order domain mapping
  • complex nested DTOs
  • security-sensitive field filtering
  • APIs where fields change often

Production Pitfall: Copying Too Much

This bug is easy to miss:

BeanUtils.copyProperties(userEntity, requestDto);

If requestDto contains fields like role, status, or createdAt, you may accidentally let user input overwrite fields it should not control.

For request-to-entity updates, I prefer explicit allow-list mapping:

user.setDisplayName(request.getDisplayName());
user.setBio(request.getBio());

It is less clever. It is safer.

Final Thought

BeanUtils is a convenience tool, not an architecture.

Use it where the mapping is boring. When the mapping carries business meaning, write it so the next developer can see every decision.

Have you ever had a DTO copy bug caused by a field you did not mean to map?

相关阅读

Java final, finally, finalize: Three Bugs They Prevent

A practical Java explanation of final, finally, and finalize using real failure modes instead of memorized definitions.

java

Java throw vs throws: The Exception Bug They Reveal

A practical Java exception handling guide explaining throw, throws, checked exceptions, runtime exceptions, and API boundary decisions.

java

Debug a Slow MySQL Query Before You Guess at Indexes

A practical MySQL workflow for finding slow queries, reading EXPLAIN output, and deciding whether an index actually helps.

mysql

原文发布

本文首发于 dev.to,评论与点赞保留在原站。

在 dev.to 继续阅读
上一篇RedisJSON Is Useful When You Update Parts of a DocumentA practical RedisJSON walkthrough: when to use it, when not to, and the commands that actually matter.
返回全部文章
下一篇Network Address Calculation: The Subnet Math That MattersA practical subnetting guide showing how to calculate a network address from an IP address and mask using binary math and simple examples.
返回档案
M4RKYUM4RKYUM4RKYUM4RKYUM4RKYUM4RKYUM4RKYUM4RKYU
始于 2024
ZhenXiao Mark YuZhenXiao Mark Yu
联系

看到什么有意思的?和我聊聊。

这是一个作品集,不是服务 · 但每一条留言我都会看 — 如果哪里让你有所触动,或者只想打个招呼,欢迎写信过来。

开启对话
频道开放

随时打个招呼 · 2026

--:--:--EST加拿大 安大略
  • 邮件
  • GitHub
  • dev.to
  • 领英
  • 推特 / X
  • Instagram
  • Facebook
  • YouTube
  • CodePen
  • Spotify
  • Snapchat

订阅

偶尔收到一封简讯

来自 m4rkyu.com 的笔记与日志——简短、标注日期、没有杂音。随时可退订。

作品

线上发布、游戏作品与视觉档案。

  • 项目
  • 游戏
  • 档案
  • 日志

资源

每日好用的工具与个人收藏的链接库。

  • 搜索
  • 最新
  • 工具
  • 链接
  • 笔记
  • 主题
  • 商店
RSSJSON Feed

工作室

背景、联系方式以及合作渠道。

  • 关于
  • 联系
  • 更新日志
  • 技术说明
  • 简历筹备中

社交

在常去的平台上找到我。

  • GitHub
  • dev.to
  • 领英
  • 推特 / X
  • Instagram
  • Facebook
  • YouTube
  • CodePen
  • Spotify
  • Snapchat
  • 邮件
© 2026 ZhenXiao Mark Yumarkyu0615@gmail.com
  • 邮件
  • GitHub
  • dev.to
  • 领英
  • 推特 / X
  • Instagram
  • Facebook
  • YouTube
  • CodePen
  • Spotify
  • Snapchat
隐私条款由 Next.js 16 · React 19 · Tailwind 4 构建