当前位置:网站首页>Why is it not recommended to use BeanUtils in production?
Why is it not recommended to use BeanUtils in production?
2022-07-03 01:28:00 【Morning Xi light】
The main reason for not recommending is :
Some attribute copying tools have poor performance
Some attribute copying tools have “BUG” send
There are some hidden dangers when using attribute copying tools ( Later examples will talk about )
Example
First of all, the company has encountered commons Bag BeanUtils A real case of poor property copy performance , Then the colleague changed to Spring Of BeanUtils The performance is much better , If you are interested, you can use the performance test framework or benchmark framework to compare , There is no comparison here .
Now let's see Spring Of BeanUtils What are the problems with copying the properties of :
import lombok.Data;
import java.util.List;
@Data
public class A {
private String name;
private List<Integer> ids;
}
@Data
public class B {
private String name;
private List<String> ids;
}
import org.springframework.beans.BeanUtils;
import java.util.Arrays;
public class BeanUtilDemo {
public static void main(String[] args) {
A first = new A();
first.setName("demo");
first.setIds(Arrays.asList(1, 2, 3));
B second = new B();
BeanUtils.copyProperties(first, second);
for (String each : second.getIds()) {// Type conversion exception
System.out.println(each);
}
}
}
When you run the above example , A type conversion exception occurs .
At the break point, you can see , After the attribute is copied B Type of second In the object ids Still for Integer type :

If not converted to a string , Print directly , No errors are reported .
Use CGlib Not defined in Converter Similar problems will be encountered in the case of :
import org.easymock.cglib.beans.BeanCopier;
import java.util.Arrays;
public class BeanUtilDemo {
public static void main(String[] args) {
A first = new A();
first.setName("demo");
first.setIds(Arrays.asList(1, 2, 3));
B second = new B();
final BeanCopier beanCopier = BeanCopier.create(A.class, B.class, false);
beanCopier.copy(first,second,null);
for (String each : second.getIds()) {// Type conversion exception
System.out.println(each);
}
}
}
Again , The problem is exposed at runtime .
Let's take a look mapstruct:
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;
@Mapper
public interface Converter {
Converter INSTANCE = Mappers.getMapper(Converter.class);
B aToB(A car);
}
import java.util.Arrays;
public class BeanUtilDemo {
public static void main(String[] args) {
A first = new A();
first.setName("demo");
first.setIds(Arrays.asList(1, 2, 3));
B second = Converter.INSTANCE.aToB(first);
for (String each : second.getIds()) {// normal
System.out.println(each);
}
}
}
Can succeed in A in List<Integer> To B Medium List<String> type .
Let's look at the compiled Converter Implementation class :
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Generated;
import org.springframework.stereotype.Component;
@Generated(
value = "org.mapstruct.ap.MappingProcessor",
comments = "version: 1.3.1.Final, compiler: javac, environment: Java 1.8.0_202 (Oracle Corporation)"
)
@Component
public class ConverterImpl implements Converter {
@Override
public B aToB(A car) {
if ( car == null ) {
return null;
}
B b = new B();
b.setName( car.getName() );
b.setIds( integerListToStringList( car.getIds() ) );
return b;
}
protected List<String> integerListToStringList(List<Integer> list) {
if ( list == null ) {
return null;
}
List<String> list1 = new ArrayList<String>( list.size() );
for ( Integer integer : list ) {
list1.add( String.valueOf( integer ) );
}
return list1;
}
}
Automatically helped us with the conversion , We may not realize that the types are inconsistent .
If we were A Add one to the class String number attribute , stay B Add one to the class Long number attribute , Use mapstruect When number When it is set to non numeric type, it will report .NumberFormatException.
@Override
public B aToB(A car) {
if ( car == null ) {
return null;
}
B b = new B();
b.setName( car.getName() );
if ( car.getNumber() != null ) { // Here's the problem
b.setNumber( Long.parseLong( car.getNumber() ) );
}
b.setIds( integerListToStringList( car.getIds() ) );
return b;
}
Use cglib By default, there is no mapping number attribute ,B Medium number by null.
If you define the converter manually , Use IDEA plug-in unit ( Such as generateO2O) Automatic conversion :
public final class A2BConverter {
public static B from(A first) {
B b = new B();
b.setName(first.getName());
b.setIds(first.getIds());
return b;
}
}
This problem can be found very clearly in the coding phase :

Conclusion
because Java Generics are actually compile time checks , Post compilation generic erasure , Causes the runtime to List<Integer> and List<String> All are List type , It can be assigned normally . This leads to when using many attribute mapping tools , It is not easy to make obvious errors at compile time .
mapstruct Custom annotation processor , The generic types on both sides of the map can be read at compile time , Then map . But this mapping is also terrible , Sometimes we define the wrong type due to carelessness and other reasons , Automatically helped us with the conversion , It will bring a lot of side effects .
The performance of various attribute mapping tools has been briefly compared before , give the result as follows :

Therefore, use attribute conversion tools with caution , If possible, it is recommended to customize the conversion class , Use IDEA Plug in auto fill , Very efficient , A or B Any property type in does not match , Even delete an attribute , Errors can be reported at the compilation stage , And directly call get set The efficiency is also very high , I hope I can help you !
边栏推荐
- Test shift right: Elk practice of online quality monitoring
- Kivy tutorial - example of using Matplotlib in Kivy app
- Top ten regular spot trading platforms 2022
- Esp32 simple speed message test of ros2 (limit frequency)
- tp6快速安装使用MongoDB实现增删改查
- [Cao gongzatan] after working in goose factory for a year in 2021, some of my insights
- 【FPGA教程案例5】基于vivado核的ROM设计与实现
- 如今少年已归来,人间烟火气最抚凡人心 复工了~
- Expérience de recherche d'emploi d'un programmeur difficile
- 一比特苦逼程序員的找工作經曆
猜你喜欢

Leetcode 2097 - Legal rearrangement of pairs

软考信息系统项目管理师_历年真题_2019下半年错题集_上午综合知识题---软考高级之信息系统项目管理师053
![[principles of multithreading and high concurrency: 2. Solutions to cache consistency]](/img/ce/5c41550ed649ee7cada17b0160f739.jpg)
[principles of multithreading and high concurrency: 2. Solutions to cache consistency]

Give you an array numbers that may have duplicate element values. It was originally an array arranged in ascending order, and it was rotated once according to the above situation. Please return the sm

Meituan dynamic thread pool practice ideas, open source

【无标题】

每日一题之干草堆的移动
![[C language] detailed explanation of pointer and array written test questions](/img/24/c2c372b5c435cbd6eb83ac34b68034.png)
[C language] detailed explanation of pointer and array written test questions

音程的知识的总结

MySQL basic usage 02
随机推荐
Key wizard hit strange learning - automatic path finding back to hit strange points
wirehark数据分析与取证A.pacapng
攻克哈希的基本概念与实现
leetcode 6103 — 从树中删除边的最小分数
Basic remote connection tool xshell
Excel if formula determines whether the two columns are the same
[androd] module dependency replacement of gradle's usage skills
[Androd] Gradle 使用技巧之模块依赖替换
What are the trading forms of spot gold and what are the profitable advantages?
Is there anything in common between spot gold and spot silver
Database SQL language 01 where condition
leetcode:701. Insertion in binary search tree [BST insertion]
The meaning of wildcard, patsubst and notdir in makefile
[shutter] animation animation (shutter animation type | the core class of shutter animation)
Matlab Doppler effect produces vibration signal and processing
Swiftui component Encyclopedia: using scenekit and swiftui to build interactive 3D pie charts (tutorial with source code)
The difference between tail -f, tail -f and tail
Mathematical knowledge: divisible number inclusion exclusion principle
The industrial scope of industrial Internet is large enough. The era of consumer Internet is only a limited existence in the Internet industry
看疫情之下服装企业如何顺势而为