我的映射器的映射器装饰器没有被编译。正在编译映射器,但没有编译装饰器。因为,在构建过程中,我会遇到类型转换错误,尽管我是在映射器装饰器中进行的。还有什么要补充的吗?
映射程序代码:
@Mapper
@DecoratedWith(OneMapperDecorator.class)
public interface OneMapper {
public TwoObject convertToTwoObject(OneObject one);
}
装饰器代码:
public abstract class OneMapperDecorator implements OneMapper {
private final OneMapper delegate;
public OneMapperDecorator (OneMapper delegate) {
this.delegate = delegate;
}
@Override
public TwoObject convertToTwoObject(OneObject one)
{
TwoObject two=delegate.convertToTwoObject(one);
two.setTotalFare(new BigDecimal(one.getPrice()));//string to bigdecimal conversion
return two;
}
}
decorator的作用是增强映射而不是替换它。MapStruct无法知道您正在decorator中映射totalFare
。您有两个选项:
定义自定义映射方法
在OneMapper
中,您可以添加一个默认方法来执行映射(如错误所示。
@Mapper
@DecoratedWith(OneMapperDecorator.class)
public interface OneMapper {
@Mapping(target = "totalFare", source = "price");
TwoObject convertToTwoObject(OneObject one);
default BigDecimal map(String value) {
return value == null ? null : new BigDecimal(value);
}
}
忽略映射
如果你想在装饰器中进行映射,那么你需要告诉MapStruct不要映射它
@Mapper
@DecoratedWith(OneMapperDecorator.class)
public interface OneMapper {
@Mapping(target = "totalFare", ignore = true);
TwoObject convertToTwoObject(OneObject one);
}
我的一个建议是,如果您只使用委托映射额外的字段,我会添加自定义方法或使用@AfterMapping
和@BeforeMapping
来处理。