在 MapStruct 版本 1.1.0.Final 中,这是可能的....
@Mappings({
@Mapping(target = "transaction.process.details", expression = "java(MappingHelper.mapDetails(request))"),
//more mappings
})
Response requestToResponse(Request request);
这是可能的,因为
mapDetails
方法(巧合?)生成到 requestToResponse
方法中。这就是为什么 request
不为空。
现在,由于 1.1.0.Final 无法与 Lombok 配合使用,我必须升级到 1.2.0.CR2。在此版本中,
mapDetails
将生成为一个单独的方法,其中 request
未传递,因此 request
现在在此方法中为 null,并且我得到带有表达式的 NPE。 (现在是requestToResponse
的子子方法。)
我是否误用了这个表达方式,它只是巧合,还是新版本有错误?如果没有错误,我如何正确地将
request
实例传递给表达式?
您曾经/正在滥用该表达方式。您需要做的是将目标映射到源参数。
@Mapper(uses = { MappingHelper.class })
public interface MyMapper {
@Mappings({
@Mapping(target = "transaction.process.details", source = "request"),
//more mappings
})
Response requestToResponse(Request request);
}
然后,MapStruct 应创建中间方法并使用
MappingHelper
并调用 mapDetails
方法。如果您有多种从 Request
映射到 details
的任何类型的方法,那么您将需要使用合格的映射(请参阅文档中的更多here)。
它看起来像:
public class MappingHelper {
@Named("mapDetails") // or the better type safe one with the meta annotation @Qualifier
public static String mapDetails(Request request);
}
您的映射将如下所示:
@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);
}