Mastering Java Object Copying: Apache vs Spring BeanUtils Compared
This article explains the difference between shallow and deep copying in Java, demonstrates how Apache Commons BeanUtils and Spring Framework BeanUtils perform property copying with code examples, highlights performance concerns, and recommends more efficient alternatives for backend development.
In Java projects, copying properties between different object types such as DTO and DO is a common requirement, but writing manual getters and setters is tedious.
Shallow vs Deep Copy
Java distinguishes between primitive values and object references. Assigning with “=” copies the value for primitives but only copies the reference for objects. A shallow copy duplicates primitive fields and copies references, while a deep copy creates a new instance for referenced objects and copies their contents.
Apache Commons BeanUtils
Apache BeanUtils provides a copyProperties method that performs a shallow copy by default. The article shows a simple example with PersonSource and PersonDest classes and demonstrates the call BeanUtils.copyProperties(dest, source). The underlying implementation validates beans, handles DynaBeans, Maps, and standard JavaBeans, and uses reflection to copy each readable and writable property.
Ali-Check recommends avoiding Apache BeanUtils for property copying due to its poor performance.
Spring Framework BeanUtils
Spring’s BeanUtils also offers a copyProperties method, but its implementation is simpler: it copies matching property names via direct getter/setter calls, checks accessibility, and allows optional ignore lists and editable class constraints. Example code shows copying between the same PersonSource and PersonDest objects.
The Spring version ensures type compatibility and skips properties that are not present or are ignored, making it safer for mismatched structures.
Conclusion
Because Apache BeanUtils suffers from performance drawbacks, the article recommends using Spring’s BeanUtils or alternative libraries such as CGLIB’s BeanCopier or Orika for more efficient object mapping.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Code Ape Tech Column
Former Ant Group P8 engineer, pure technologist, sharing full‑stack Java, job interview and career advice through a column. Site: java-family.cn
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
