映射装饰器未得到编译

时间:2018-12-05 12:52:18

标签: spring-mvc java-8 mapstruct

我的映射器的映射器装饰器没有被编译,映射器正在被编译,但装饰器没有被编译。因为在构建期间,即使在映射器装饰器中执行此操作,也遇到类型转换错误。还有什么要补充的吗?

映射器代码:

 @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;
            }
}

1 个答案:

答案 0 :(得分:2)

装饰器旨在增加映射而不是替换它。 MapStruct无法知道您正在装饰器中映射totalFare。您有2个选择:

定义自定义映射方法

在您的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来处理。