为什么不推荐使用BeanUtils属性转换工具
来源:https://blog.csdn.net/w605283073
1. 背景
2. 示例
接下来我们看 Spring 的 BeanUtils 的属性拷贝会存在啥问题:
import lombok.Data;
import java.util.List;
@Data
public class A {
private String name;
private List<Integer> ids;
}
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()) {// 类型转换异常
System.out.println(each);
}
}
}
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()) {// 类型转换异常
System.out.println(each);
}
}
}
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;
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()) {// 正常
System.out.println(each);
}
}
}
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Generated;
import org.springframework.stereotype.Component;
(
value = "org.mapstruct.ap.MappingProcessor",
comments = "version: 1.3.1.Final, compiler: javac, environment: Java 1.8.0_202 (Oracle Corporation)"
)
public class ConverterImpl implements Converter {
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;
}
}
public B aToB(A car) {
if ( car == null ) {
return null;
}
B b = new B();
b.setName( car.getName() );
if ( car.getNumber() != null ) { // 问题出在这里
b.setNumber( Long.parseLong( car.getNumber() ) );
}
b.setIds( integerListToStringList( car.getIds() ) );
return b;
}
public final class A2BConverter {
public static B from(A first) {
B b = new B();
b.setName(first.getName());
b.setIds(first.getIds());
return b;
}
}
3. 结论
往 期 推 荐 1、最牛逼的 Java 日志框架,性能无敌,横扫所有对手! 2、把Redis当作队列来用,真的合适吗? 3、惊呆了,Spring Boot居然这么耗内存!你知道吗? 4、牛逼哄哄的 BitMap,到底牛逼在哪? 5、全网最全 Java 日志框架适配方案!还有谁不会? 6、30个IDEA插件总有一款适合你 7、Spring中毒太深,离开Spring我居然连最基本的接口都不会写了
点分享
点收藏
点点赞
点在看
评论