Analysis of the problem of using BeanUtils.copyProperties method object in java to copy fields with the same name but different types and assigning empty values

Project scenario:

Copying between objects, the field type in the dto object is String, and the field type in the model is BigDecimal. Use the BeanUtils.copyProperties method to copy objects in batches.


Problem Description

提示:这里描述项目中遇到的问题:

Use Spring's BeanUtils.copyProperties method to find that the String type field in the dto cannot be converted to the BigDecimal type field with the same name in the model.


Cause Analysis:

Using Spring's BeanUtils.copyProperties method does not support assignment to fields with the same name of different types.


solution:

Replace Spring的BeanUtils.copyProperties method with Apache Commons BeanUtils的copyProperties method.

Code analysis:

1. The copyProperties method of Apache Commons BeanUtils

  1. Utility methods

Method usage

  1. Entry method

Insert image description here

  1. Get the name and value of the field

Insert image description here

  1. There is a coverForCopy method in the copyPropertry method, which copies the fields and performs type conversion.

Insert image description here

Insert image description here

  1. Get the field type in the target object and convert the value.

Insert image description here
Insert image description here
Insert image description here

Finally, the String type is assigned to the field of the same name of the BigDecimal type.

Reasons:
1. There is no built-in type conversion function in Spring's BeanUtils.copyProperties method. This method is mainly used to copy the attribute value of one object to another object. The copy of the attribute value is matched according to the field name.
If the field type of the source object does not match the field type of the target object, Spring's BeanUtils.copyProperties method will directly copy the field value without performing type conversion. This means that if the source object's field type is String, and the target object's field type is BigDecimal, the string will not be automatically converted to BigDecimal.

2. When copying properties, the copyProperties method of Apache Commons BeanUtils will perform corresponding conversions based on the types of the source object fields and the target object fields.
When the corresponding field types of the source object and the target object are inconsistent, BeanUtils attempts to perform type conversion. It uses Java's built-in type conversion mechanism and some custom conversion rules to handle conversions between different types.
When performing type conversions, BeanUtils uses built-in conversion rules whenever possible, such as using the appropriate constructor or conversion method. If the default rules cannot handle conversion, you can register a custom converter to handle conversion between specific types.

Guess you like

Origin blog.csdn.net/hurtseverywhere/article/details/131598032