wrong output: 4
wrong output: 4
wrong output: 4
wrong output: 4
This could happen if the list is containing same object, then Why is list containing same object and how could following work?
correct output: 1
correct output: 2
correct output: 3
correct output: 4
origCustomer is containing reference to say CustomerDTO@60bc92, which is singleton maintained by spring, So it would always have same reference. Reference for targetCustomer will change. But BeanUtils.copyProperties(targetCustomer, origCustomer); will copy the properties of targetCustomer to origCustomer means CustomerDTO@60bc92.
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(customer ids 1 to 4){
customer will get reference CustomerDTO@60bc92 and will be updated based on customer ids
so it is printing correct values
but it is adding same reference CustomerDTO@60bc92 to the list
}
for(CustomerDTO customer: customerList){
System.out.println("wrong output: "+customer.getCustomerId());//getting wrong output here
}
for(all customer object in list which is same object reference and having latest value means 4){
it is printing wrong value as 4
}
Now why origCustomer is being created from Spring context, like
CustomerDTO origCustomer = _springContext.getBean(CustomerDTO.class);
Because BeanUtils from spring needs default initialized spring bean.
Solution of this problem:
CustomerDTO origCustomer = new CustomerDTO();
and using BeanUtils from org.apache.commons.beanutils.BeanUtils;