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()
。だから私はこの投稿に従って浅いクローニングを使用しようとします。
更新: 使用するのが間違っていたため、不変性という言葉を削除しました。