在 MapStruct 版本 1.1.0.Final 中,这是可能的....
@Mappings({
@Mapping(target = "transaction.process.details", expression = "java(MappingHelper.mapDetails(request))"),
//more mappings
})
Response requestToResponse(Request request);
Run Code Online (Sandbox Code Playgroud)
这是可能的,因为该mapDetails方法是(巧合?)生成到requestToResponse方法中的。这就是为什么request不为空的原因。
现在,由于 1.1.0.Final 不适用于 Lombok,我不得不升级到 1.2.0.CR2。在这个版本中,mapDetails将生成到一个单独的方法中,request没有传递,所以request现在在这个方法中为空,我得到了一个带有表达式的 NPE。(这是现在的子子方法requestToResponse。)
我是否误用了这个表达式,所以它只是巧合,还是新版本有错误?如果没有错误,我该如何request正确地将实例传递给表达式?
您曾/正在滥用该表达式。您需要做的是将目标映射到源参数。
@Mapper(uses = { MappingHelper.class })
public interface MyMapper {
@Mappings({
@Mapping(target = "transaction.process.details", source = "request"),
//more mappings
})
Response requestToResponse(Request request);
}
Run Code Online (Sandbox Code Playgroud)
MapStruct 然后应该创建中间方法并使用MappingHelper和 调用该mapDetails方法。如果你有多个方法是从地图Request到任何类型details的,那么你将需要使用合格的映射(详见这里的文档)。
它看起来像:
public class MappingHelper {
@Named("mapDetails") // or the better type safe one with the meta annotation @Qualifier
public static String mapDetails(Request request);
}
Run Code Online (Sandbox Code Playgroud)
您的映射将如下所示:
@Mapper(uses = { MappingHelper.class })
public interface MyMapper {
@Mappings({
@Mapping(target = "transaction.process.details", source = "request", qualifiedByName = "mapDetails"), //or better with the meta annotation @Qualifier qualifiedBy
//more mappings
})
Response requestToResponse(Request request);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11636 次 |
| 最近记录: |