当Source为null时,另一个bean属性的默认值。MapStruct

时间:2020-10-21 22:01:58

标签: java mapstruct

好吧,我在MapStruct中有以下Mapper:

 @Mapping(source = "payload.after", target = "payload")
 TargetEntity toTarget(SourceEntity source);

有时payload.after为空,我需要填充另一个名为payload.before的属性。像这样:

 @Mapping(source = "payload.after", target = "payload")
   //OR, if payload.after is null
 @Mapping(source = "payload.before", target = "payload")
 TargetEntity toTarget(SourceEntity source);

我尝试过以这种方式使用,但没有用:

 @Mapping(source = "payload.after", target = "payload", defaultValue = "payload.before")
 TargetEntity toTarget(SourceEntity source);

有办法吗?

1 个答案:

答案 0 :(得分:1)

从MapStruct文档中,我看到只有您可以使用预定义的值:https://mapstruct.org/documentation/stable/reference/html/#default-values-and-constants

但是您可以通过在MapStruct文档示例中使用@AfterMapping@BeforeMapping之类的注释来轻松实现:)

编辑:

@Mapping(target = "otherTargetField", source = "otherSrcField")
TargetEntity toTarget(SourceEntity source);

@AfterMapping
void toTargetAfterMapping(@MappingTarget TargetEntity, SourceEntity source) {
   // Your after mapping logic with payload.before and payload.after
}

MapStruct自动解析在最后一个return语句之前的映射方法的末尾调用此方法。如果您想了解更多信息,请参见MapStruct docs - customising mappings with before and after

您可以使用的另一种方法是defaultExpression

@Mapping(target = "payload", source = "payload.after", defaultExpression = "java(source.getPayload().getBefore())")
TargetEntity toTarget(SourceEntity source);