在@Mapper中使用多个参数时,似乎@Context参数不可访问
public interface MyMapper {
@Mapping(target="target1", source="arg1.arg") //works
@Mapping(target="target2", source="arg2") //works
@Mapping(target="target3", source="arg2.arg") //works
@Mapping(target="target2", source="context.arg") //NOT WORKING
public MyTarget convert(Object arg1, Object arg2, @Context Object context);
}
我正在尝试使用和expression=""
来解决它,但是我无法使其工作。
有什么建议吗?
我可以看出,我并不是唯一一个希望这样做的人。 https://github.com/mapstruct/mapstruct/issues/1280
谢谢
答案 0 :(得分:2)
要回答第二个问题:
public interface MyMapper {
@Mapping(target="target1", source="arg1.arg")
@Mapping(target="target2", ignore = true ) // leave to after mapping
MyTarget convert(Object arg1, @Context Object context);
@AfterMapping
default convert(Object arg1, @MappingTarget MyTarget target, @Context context) {
target.setTarget2( convert ( context ) );
}
// if you have multipe mappings, you could address them here
@Mapping(target="target2", source="context.arg")
MyInnerTarget convert(Object arg1, Object context);
}
答案 1 :(得分:1)
根据定义,@Context
带注释的对象不是源。这是上下文,因此您不能在source
@Mapping(target="target2", source="context.arg")
答案 2 :(得分:0)
我遇到了与需要@Context
参数才能传递给嵌套映射函数的情况相同的场景,但是我还想将其用作@Mapping
中的源。我可以使用expression
来实现此目标,如下所示:
public interface MyMapper {
@Mapping(target="target1", source="arg1")
@Mapping(target="target2", source="arg2")
@Mapping(target="target3", expression="java( contextArg )")
public MyTarget convert(Object arg1, Object arg2, @Context Object contextArg);
}