public class CustomerDTO {
private int customerId;
private String customerName;
private String customerAddress;
public int getCustomerId() {
return customerId;
}
public void setCustomerId(int customerId) {
this.customerId = customerId;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getCustomerAddress() {
return customerAddress;
}
public void setCustomerAddress(String customerAddress) {
this.customerAddress = customerAddress;
}
}
CustomerDAO 类:
import java.util.ArrayList;
import java.util.List;
import java.util.Collections;
public final class CustomerDAO {
private CustomerDTO customer;
public void setCustomer(CustomerDTO customer) {
this.customer = customer;
}
//Trying to get copy of object with BeanUtils
public final CustomerDTO getCustomer(int customerId){
CustomerDTO origCustomer = _springContext.getBean(CustomerDTO.class);
CustomerDTO targetCustomer=null;
if("you get customer based on customer id") then "targetCustomer got initialized";
BeanUtils.copyProperties(targetCustomer, origCustomer);//spring BeanUtils
}
//Trying to add object returned by above method into the list
public final List<CustomerDTO> getCustomerList(List<Integer> customerIds){
List<CustomerDTO> customerList = new ArrayList<CustomerDTO>();
for(Integer id:customerIds){
CustomerDTO customer = getCustomer(id);
System.out.println("correct output: "+customer.getCustomerId());//getting correct output here
customerList.add(customer);//Trying to add copied object in list
}
for(CustomerDTO customer: customerList){
System.out.println("wrong output: "+customer.getCustomerId());//getting wrong output here
}
return Collections.unmodifiableList(customerList);
}
}
在CustomerDTO getCustomer(int customerId)
方法中,我试图通过使用 Spring 返回 CustomerDTO 对象的副本BeanUtils.copyProperties(targetCustomer, origCustomer);
,但是当我在方法中的列表中添加这些复制的对象时,List<CustomerDTO> getCustomerList(List<Integer> customerIds)
我得到了评论中提到的奇怪行为。如果我要删除BeanUtils.copyProperties(targetCustomer, origCustomer);
,那么行为是正确的。
测试用例:
getCustomerList with customerIds =[1,2,3,4]
使用复制的对象: BeanUtils.copyProperties(targetCustomer, origCustomer);
//spring BeanUtils
correct output: 1
correct output: 2
correct output: 3
correct output: 4
wrong output: 4
wrong output: 4
wrong output: 4
wrong output: 4
没有复制的对象: BeanUtils.copyProperties(targetCustomer, origCustomer);
//spring BeanUtils
correct output: 1
correct output: 2
correct output: 3
correct output: 4
wrong output: 1
wrong output: 2
wrong output: 3
wrong output: 4
有人可以解释一下这种行为有什么问题或可能的解释吗?
更新:使用 BeanUtils 的目的:
我试图在从方法返回 CustomerDTO 对象之前使用可变对象的防御性副本getCustomer()
。所以我尝试在这篇文章之后使用浅克隆。
更新:删除了 Immutability 这个词,因为它是错误的使用。