BeanUtils.copyProperties using springboot under Lombok annotation is invalid

Problem phenomenon:

Used in the project today 

BeanUtils.copyProperties(userInfo, bladeUserVo);

Copy all the attribute values ​​of the userInfo object to the attributes of the same name of the bladeUserVo object . But it failed .


problem analysis:

By looking at the code, we can know:

Because the entity class original objects used in lombok plug of @Getter and @Setter comment.

And BeanUtils.copyProperties(A, B); first find the getter and setter methods in the A object , and then find the getter and setter methods in the B object, and match the corresponding method by the property name , so as to realize the property value copy,

However, after only using the lombok plug- in, the processing logic of the getter and setter methods in the A object will be changed, which is different from the original java logic :

lombok plug arranged @Accessors (chain = true) annotation, the annotation can be acted setter methods return values of the object, from the original void to attribute types (e.g., String, int, Integer, etc.).


Solution:

1. Do not use lombok plugin :

In fact, although the lombok plug-in makes the code look convenient, it is larger after packaging, because the logic of the getter/setter method has not changed much, but there is an additional plug-in dependency package.

It is better to manually define the getter/setter methods yourself , and you can also avoid the compatibility problems of some methods (such as BeanUtils.copyProperties(A, B) ). In fact, old IDEA drivers know that there are shortcut keys (Alt+Insert) that can directly generate entity classes.  Methods such as getter/setter/toString/constructor are  not more time-consuming than lombok.

 

2. Call the getter method of the properties that need to be used in the A object, and assign the setter methods corresponding to the B object one by one to the properties of the B object with the same name.

 

3. Modify the logic. For specific operating principles and examples, you can check the link of this big guy (reproduced):

https://www.jianshu.com/p/357b55852efc

Guess you like

Origin blog.csdn.net/weixin_42585386/article/details/112790028