@AfterMapping 方法在生成的类中未调用

Ami*_*ira 5 mapstruct

我正在尝试自定义映射,使用字符串来确定对象属性,因此我写了以下内容:

@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE)
public abstract class ProductMapper {

public abstract ProductInput asProductInputFromIdentifier(String identifier);

@AfterMapping
protected void determineIdentifier(String identifier, @MappingTarget ProductInput out) {
    if (StringUtils.contains(identifier, '?')) {
        out.setExternalId(identifier);
    } else {
        out.setInernalId(identifier);
    }
}
}
Run Code Online (Sandbox Code Playgroud)

生成的类不会调用确定标识符方法。我通过直接在asProductInputFromIdentifier方法上使用 Java 表达式找到了另一个解决方案,但我真的想使用@AfterMapping编写清晰的代码。

@Mapping(target = "externalId", expression = "java( org.apache.commons.lang3.StringUtils.contains(identifier, '|') ? identifier : null )")
@Mapping(target = "internalId", expression = "java( !org.apache.commons.lang3.StringUtils.contains(identifier, '|') ? identifier : null )")
public abstract ProductInput asProductDetailInputFromIdentifier(String identifier);
Run Code Online (Sandbox Code Playgroud)

我不明白为什么它不起作用是因为我在方法参数中没有对象吗?

Moh*_*BLI 6

如果有 lombok @Builder,则 afterMapping 将永远不会被调用。

问题始终没有解决。

在此处查看官方存储库上的问题


Rak*_*han 5

方法@AfterMapping将在map方法的末尾执行,并且它应该具有与map方法相同的输入参数,例如下面的示例

@Mapper(
    componentModel = "spring",
    injectionStrategy = InjectionStrategy.CONSTRUCTOR,
    uses = {IdentifierMapper.class})
public interface HistoryMapper {

  HistoryDynamo toHistoryDynamo(History history);

  @AfterMapping
  default void changeReason(History history) {
    System.out.println(history.getReason());
  }
}
Run Code Online (Sandbox Code Playgroud)

请参阅 github 工作示例以获取相同的https://github.com/rakesh-singh-samples/map-struct-samples/tree/stack-question-60523230/src/sample/mapstruct/mapper