PropertyMapper
PropertyMapper 是 Spring 框架中的工具类。
核心
PropertyMapper 类主要有四大核心:
- Source :一个存储提供值的 Supplier 与调用方法时对 Supplier 进行合法测试的 Predicate;
- SourceOperator:对 Source 实例进行处理的 lambda 接口,与 JDK 8 的 Function 接口不同的是它的返回值总是与入参相同;
- NullPointerExceptionSafeSupplier:特殊的 Supplier,供 whenNonNull 方法调用以避免空指针(返回 null 值)
- CachingSupplier:缓存 PropertyMapper 实例中的 Supplier 的返回值 result (保存在上次调用的父实例中)
静态入口方法 PropertyMapper::get
PropertyMapper 类内部维护一个静态实例,我们一开始只能通过获取它得到 PropertyMapper 实例。
public static PropertyMapper get() {
return INSTANCE;
}
实例方法 PropertyMapper::from
向 PropertyMapper 传递初始值。
public <T> PropertyMapper.Source<T> from(Supplier<T> supplier) {
Assert.notNull(supplier, "Supplier must not be null");
PropertyMapper.Source<T> source = this.getSource(supplier);
if (this.sourceOperator != null) {
source = this.sourceOperator.apply(source);
}
return source;
}
实例方法 Source::to
方法逻辑很简单,首先从由 PropertyMapper 传递进来的 CachingSupplier 中获得值,然后使用内部的 Predicate 对该值进行检查,如果检测通过则执行 Comsumer 方法。
public void to(Consumer<T> consumer) {
Assert.notNull(consumer, "Consumer must not be null");
T value = this.supplier.get();
if (this.predicate.test(value)) {
consumer.accept(value);
}
}
实例方法 Source::toInstance
实例方法 Source::whenNonNull
whenNonNull 方法继承了原有实例的 Supplier 字段,覆盖了原有的 Predicate 字段以供后续值判断或者条件附加使用。
1、将源属性映射到目标属性
PropertyMapper map = PropertyMapper.get();
map.from(source::getName)
.to(destination::setName);