空值处理
默认情况下,BeanUtils
会从源对象拷贝所有未忽略的字段到目标对象。某些情况下,使用者可能只希望拷贝非空的值到目标对象,或者忽略特定字段的空值。此时可以通过BeanUtils
提供的额外参数,或配置@Mapping(mapNull=false)
满足上述需求。
class Foo {
String name = "foo";
String content = "content";
}
class FooDto {
@Mapping(mapNull=false)
String name;
String content;
}
Foo foo = new Foo();
FooDto fooDto = new FooDto();
BeanUtils.copyProperties(fooDto, foo, false); // 空值全部忽略
System.out.println(foo.getName()); // "foo"
System.out.println(foo.getContent()); // "content"
BeanUtils.copyProperties(fooDto, foo); // 默认不忽略,读取@Mapping配置
System.out.println(foo.getName()); // "foo"
System.out.println(foo.getContent()); // null
Last updated