我正在尝试自定义映射,使用字符串来确定对象属性,因此我写了以下内容:
@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)
我不明白为什么它不起作用是因为我在方法参数中没有对象吗?
方法@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
| 归档时间: |
|
| 查看次数: |
7998 次 |
| 最近记录: |