两个包下的BeanUtils.copyProperties有什么不同?
时间: 2024-05-24 16:09:00 浏览: 18
这两个包中的 `copyProperties` 方法都可以用于将一个JavaBean的属性值赋值到另一个JavaBean中,但是两个方法的实现有所不同。`org.springframework.beans.BeanUtils` 包下的 `copyProperties` 方法只进行浅拷贝,而 `org.apache.commons.beanutils.BeanUtils` 包下的 `copyProperties` 方法可以通过参数配置实现浅拷贝和深拷贝。具体来说,浅拷贝只拷贝JavaBean对象本身的属性值,如果属性值是引用类型,则只复制引用地址。而深拷贝会递归地将所有属性值都进行复制,即使属性值是引用类型也会递归拷贝其内部的属性值。
下面是两个包中 `copyProperties` 的不同实现方式的范例代码:
1. `org.springframework.beans.BeanUtils` 包下的 `copyProperties` 只进行浅拷贝,范例如下:
```java
import org.springframework.beans.BeanUtils;
public class Source {
private int id;
private String name;
public Source(int id, String name) {
this.id = id;
this.name = name;
}
// getters and setters
}
public class Target {
private int id;
private String name;
public Target() {}
// getters and setters
}
Source source = new Source(1, "test");
Target target = new Target();
BeanUtils.copyProperties(source, target);
System.out.println(target.getId()); // 输出:1
System.out.println(target.getName()); // 输出:test
```
2. `org.apache.commons.beanutils.BeanUtils` 包下的 `copyProperties` 可以通过参数控制是否进行深拷贝,范例如下:
```java
import org.apache.commons.beanutils.BeanUtils;
public class Source {
private int id;
private String name;
public Source(int id, String name) {
this.id = id;
this.name = name;
}
// getters and setters
}
public class Target {
private int id;
private String name;
public Target() {}
// getters and setters
}
Source source = new Source(1, "test");
Target target = new Target();
BeanUtils.copyProperties(target, source);
System.out.println(target.getId()); // 输出:1
System.out.println(target.getName()); // 输出:test
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)