要使用mapstruct映射某个对象,我需要一些自定义后期处理,这需要一个额外的参数来完成它的工作:
@Mapper
public abstract class AlertConfigActionMapper {
@Mappings({ @Mapping(target = "label", ignore = true)})
public abstract AlertConfigActionTO map (AlertConfigAction action, Locale userLanguage);
@AfterMapping
public void setLabel (AlertConfigAction action, @MappingTarget AlertConfigActionTO to, Locale userLanguage) {
for (AlertConfigActionLabel label : action.getAlertConfigActionLabels()) {
if (label.getLanguage().equals(userLanguage)) {
to.setLabel(label.getLabel());
break;
} else if (label.getLanguage().equals(Locale.ENGLISH)) {
to.setLabel(label.getLabel());
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
这很好用.当我向此映射器添加以下方法时,问题开始:
public abstract ArrayList<AlertConfigActionTO> mapList (List<AlertConfigAction> actions, Locale userLanguage);
Run Code Online (Sandbox Code Playgroud)
我需要传递这个参数(userLanguage),但是在这种情况下mapstruct似乎"分解":我为这部分生成以下代码(这自然会产生编译错误):
@Override
public List<AlertConfigActionTO> mapList(List<AlertConfigAction> actions, Locale userLanguage) {
if ( actions == null && userLanguage == null ) {
return null;
}
List<AlertConfigActionTO> list = new List<AlertConfigActionTO>();
return list;
}
Run Code Online (Sandbox Code Playgroud)
我确定它与参数有关,因为如果我删除它(从所有映射方法),则正确生成mapList方法.
在这种情况下,需要做什么才能允许自定义参数?
我知道这个问题很老了,但是我遇到了这个问题,从 mapstruct 1.2 版本开始,你可以使用@Context解决它
因此声明列表的映射需要像这样:
public abstract ArrayList<AlertConfigActionTO> mapList (List<AlertConfigAction> actions, @Context Locale userLanguage);
Run Code Online (Sandbox Code Playgroud)
现在,您只需要添加另一个非抽象映射,如下所示:
public AlertConfigActionTO mapConcrete (AlertConfigAction action, @Context Locale userLanguage){
return map (action, userLanguage);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2417 次 |
| 最近记录: |