Skip to content

Commit a3c11e7

Browse files
committed
Bean映射工具之Apache BeanUtils VS Spring BeanUtils
1 parent fa97f44 commit a3c11e7

File tree

2 files changed

+221
-2
lines changed

2 files changed

+221
-2
lines changed

README.md

+3-2
Original file line numberDiff line numberDiff line change
@@ -40,8 +40,9 @@
4040

4141
### 进阶
4242

43-
1. **[关于Spring中的参数校验的一点思考](./docs/advanced/spring-bean-validation.md)**
44-
2. [5分钟搞懂如何在Spring Boot中Schedule Tasks](./docs/advanced/SpringBoot-ScheduleTasks.md)
43+
1. [Bean映射工具之Apache BeanUtils VS Spring BeanUtils](./docs/advanced/Apache-BeanUtils-VS-SpringBean-Utils.md)
44+
2. **[如何在 Spring/Spring Boot 中做参数校验?你需要了解的都在这里!](./docs/advanced/spring-bean-validation.md)**
45+
3. [5分钟搞懂如何在Spring Boot中Schedule Tasks](./docs/advanced/SpringBoot-ScheduleTasks.md)
4546
4. **[新手也能看懂的 Spring Boot 异步编程指南](./docs/advanced/springboot-async.md)**
4647
5. [Spring Boot 整合 阿里云OSS 存储服务,快来免费搭建一个自己的图床](./docs/advanced/springboot-oss.md)
4748
6. [超详细,新手都能看懂 !使用Spring Boot+Dubbo 搭建一个分布式服务](./docs/advanced/springboot-dubbo.md)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,218 @@
1+
>本文转载自:[https://pjmike.github.io/2018/11/03/Bean映射工具之Apache-BeanUtils-VS-Spring-BeanUtils/](https://pjmike.github.io/2018/11/03/Bean映射工具之Apache-BeanUtils-VS-Spring-BeanUtils/),作者 pjmike 。
2+
3+
## 前言
4+
5+
在我们实际项目开发过程中,我们经常需要将不同的两个对象实例进行属性复制,从而基于源对象的属性信息进行后续操作,而不改变源对象的属性信息,比如DTO数据传输对象和数据对象DO,我们需要将DO对象进行属性复制到DTO,但是对象格式又不一样,所以我们需要编写映射代码将对象中的属性值从一种类型转换成另一种类型。
6+
7+
## 对象拷贝
8+
9+
在具体介绍两种 BeanUtils 之前,先来补充一些基础知识。它们两种工具本质上就是对象拷贝工具,而对象拷贝又分为深拷贝和浅拷贝,下面进行详细解释。
10+
11+
### 什么是浅拷贝和深拷贝
12+
13+
在Java中,除了 **基本数据类型**之外,还存在 **类的实例对象**这个引用数据类型,而一般使用 “=”号做赋值操作的时候,对于基本数据类型,实际上是拷贝的它的值,但是对于对象而言,其实赋值的只是这个对象的引用,将原对象的引用传递过去,他们实际还是指向的同一个对象。
14+
15+
而浅拷贝和深拷贝就是在这个基础上做的区分,如果在拷贝这个对象的时候,只对基本数据类型进行了拷贝,而对引用数据类型只是进行引用的传递,而没有真实的创建一个新的对象,则认为是**浅拷贝**。反之,在对引用数据类型进行拷贝的时候,创建了一个新的对象,并且复制其内的成员变量,则认为是**深拷贝**
16+
17+
简单来说:
18+
19+
- **浅拷贝**:对基本数据类型进行值传递,对引用数据类型进行引用传递般的拷贝,此为浅拷贝
20+
- **深拷贝**: 对基本数据类型进行值传递,对引用数据类型,创建一个新的对象,并复制其内容,此为深拷贝。
21+
22+
![deep and shallow copy](https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/2019-7/java-deep-and-shallow-copy.jpg)
23+
24+
## BeanUtils
25+
26+
前面简单讲了一下对象拷贝的一些知识,下面就来具体看下两种 BeanUtils 工具
27+
28+
### Apache 的 BeanUtils
29+
30+
首先来看一个非常简单的BeanUtils的例子
31+
32+
```java
33+
public class PersonSource {
34+
private Integer id;
35+
private String username;
36+
private String password;
37+
private Integer age;
38+
// getters/setters omiited
39+
}
40+
public class PersonDest {
41+
private Integer id;
42+
private String username;
43+
private Integer age;
44+
// getters/setters omiited
45+
}
46+
public class TestApacheBeanUtils {
47+
public static void main(String[] args) throws InvocationTargetException, IllegalAccessException {
48+
//下面只是用于单独测试
49+
PersonSource personSource = new PersonSource(1, "pjmike", "12345", 21);
50+
PersonDest personDest = new PersonDest();
51+
BeanUtils.copyProperties(personDest,personSource);
52+
System.out.println("persondest: "+personDest);
53+
}
54+
}
55+
persondest: PersonDest{id=1, username='pjmike', age=21}
56+
```
57+
58+
从上面的例子可以看出,对象拷贝非常简单,BeanUtils最常用的方法就是:
59+
60+
```java
61+
//将源对象中的值拷贝到目标对象
62+
public static void copyProperties(Object dest, Object orig) throws IllegalAccessException, InvocationTargetException {
63+
BeanUtilsBean.getInstance().copyProperties(dest, orig);
64+
}
65+
```
66+
67+
默认情况下,使用`org.apache.commons.beanutils.BeanUtils`对复杂对象的复制是引用,这是一种**浅拷贝**
68+
69+
但是由于 Apache下的BeanUtils对象拷贝性能太差,不建议使用,而且在**阿里巴巴Java开发规约插件**上也明确指出:
70+
71+
> Ali-Check | 避免用Apache Beanutils进行属性的copy。
72+
73+
commons-beantutils 对于对象拷贝加了很多的检验,包括类型的转换,甚至还会检验对象所属的类的可访问性,可谓相当复杂,这也造就了它的差劲的性能,具体实现代码如下:
74+
75+
```java
76+
public void copyProperties(final Object dest, final Object orig)
77+
throws IllegalAccessException, InvocationTargetException {
78+
79+
// Validate existence of the specified beans
80+
if (dest == null) {
81+
throw new IllegalArgumentException
82+
("No destination bean specified");
83+
}
84+
if (orig == null) {
85+
throw new IllegalArgumentException("No origin bean specified");
86+
}
87+
if (log.isDebugEnabled()) {
88+
log.debug("BeanUtils.copyProperties(" + dest + ", " +
89+
orig + ")");
90+
}
91+
92+
// Copy the properties, converting as necessary
93+
if (orig instanceof DynaBean) {
94+
final DynaProperty[] origDescriptors =
95+
((DynaBean) orig).getDynaClass().getDynaProperties();
96+
for (DynaProperty origDescriptor : origDescriptors) {
97+
final String name = origDescriptor.getName();
98+
// Need to check isReadable() for WrapDynaBean
99+
// (see Jira issue# BEANUTILS-61)
100+
if (getPropertyUtils().isReadable(orig, name) &&
101+
getPropertyUtils().isWriteable(dest, name)) {
102+
final Object value = ((DynaBean) orig).get(name);
103+
copyProperty(dest, name, value);
104+
}
105+
}
106+
} else if (orig instanceof Map) {
107+
@SuppressWarnings("unchecked")
108+
final
109+
// Map properties are always of type <String, Object>
110+
Map<String, Object> propMap = (Map<String, Object>) orig;
111+
for (final Map.Entry<String, Object> entry : propMap.entrySet()) {
112+
final String name = entry.getKey();
113+
if (getPropertyUtils().isWriteable(dest, name)) {
114+
copyProperty(dest, name, entry.getValue());
115+
}
116+
}
117+
} else /* if (orig is a standard JavaBean) */ {
118+
final PropertyDescriptor[] origDescriptors =
119+
getPropertyUtils().getPropertyDescriptors(orig);
120+
for (PropertyDescriptor origDescriptor : origDescriptors) {
121+
final String name = origDescriptor.getName();
122+
if ("class".equals(name)) {
123+
continue; // No point in trying to set an object's class
124+
}
125+
if (getPropertyUtils().isReadable(orig, name) &&
126+
getPropertyUtils().isWriteable(dest, name)) {
127+
try {
128+
final Object value =
129+
getPropertyUtils().getSimpleProperty(orig, name);
130+
copyProperty(dest, name, value);
131+
} catch (final NoSuchMethodException e) {
132+
// Should not happen
133+
}
134+
}
135+
}
136+
}
137+
138+
}
139+
```
140+
141+
### Spring 的 BeanUtils
142+
143+
使用spring的BeanUtils进行对象拷贝:
144+
145+
```java
146+
public class TestSpringBeanUtils {
147+
public static void main(String[] args) throws InvocationTargetException, IllegalAccessException {
148+
149+
//下面只是用于单独测试
150+
PersonSource personSource = new PersonSource(1, "pjmike", "12345", 21);
151+
PersonDest personDest = new PersonDest();
152+
BeanUtils.copyProperties(personSource,personDest);
153+
System.out.println("persondest: "+personDest);
154+
}
155+
}
156+
```
157+
158+
spring下的BeanUtils也是使用 `copyProperties`方法进行拷贝,只不过它的实现方式非常简单,就是对两个对象中相同名字的属性进行简单的get/set,仅检查属性的可访问性。具体实现如下:
159+
160+
```Java
161+
private static void copyProperties(Object source, Object target, @Nullable Class<?> editable,
162+
@Nullable String... ignoreProperties) throws BeansException {
163+
164+
Assert.notNull(source, "Source must not be null");
165+
Assert.notNull(target, "Target must not be null");
166+
167+
Class<?> actualEditable = target.getClass();
168+
if (editable != null) {
169+
if (!editable.isInstance(target)) {
170+
throw new IllegalArgumentException("Target class [" + target.getClass().getName() +
171+
"] not assignable to Editable class [" + editable.getName() + "]");
172+
}
173+
actualEditable = editable;
174+
}
175+
PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);
176+
List<String> ignoreList = (ignoreProperties != null ? Arrays.asList(ignoreProperties) : null);
177+
178+
for (PropertyDescriptor targetPd : targetPds) {
179+
Method writeMethod = targetPd.getWriteMethod();
180+
if (writeMethod != null && (ignoreList == null || !ignoreList.contains(targetPd.getName()))) {
181+
PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
182+
if (sourcePd != null) {
183+
Method readMethod = sourcePd.getReadMethod();
184+
if (readMethod != null &&
185+
ClassUtils.isAssignable(writeMethod.getParameterTypes()[0], readMethod.getReturnType())) {
186+
try {
187+
if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
188+
readMethod.setAccessible(true);
189+
}
190+
Object value = readMethod.invoke(source);
191+
if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
192+
writeMethod.setAccessible(true);
193+
}
194+
writeMethod.invoke(target, value);
195+
}
196+
catch (Throwable ex) {
197+
throw new FatalBeanException(
198+
"Could not copy property '" + targetPd.getName() + "' from source to target", ex);
199+
}
200+
}
201+
}
202+
}
203+
}
204+
}
205+
```
206+
207+
208+
209+
可以看到,成员变量赋值是基于目标对象的成员列表,并且会跳过ignore的以及在源对象中不存在,所以这个方法是安全的,不会因为两个对象之间的结构差异导致错误,但是**必须保证同名的两个成员变量类型相同**
210+
211+
## 小结
212+
213+
以上简要的分析两种BeanUtils,因为Apache下的BeanUtils性能较差,不建议使用,可以使用 Spring的BeanUtils ,或者使用其他拷贝框架,比如:**[Dozer](http://dozer.sourceforge.net/documentation/gettingstarted.html)****[ModelMapper](http://modelmapper.org/)**等等,在后面的文章中我会对这些拷贝框架进行介绍。
214+
215+
## 参考资料 & 鸣谢
216+
217+
- [谈谈 Java 开发中的对象拷贝](http://www.importnew.com/26306.html)
218+
- [细说 Java 的深拷贝和浅拷贝](https://segmentfault.com/a/1190000010648514)

0 commit comments

Comments
 (0)