When using multiple arguments in a @Mapper, it seems that the @Context arguments is unreachable
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);
}
I am trying to use and expression=""
to work around it, but I can't get it to work.
Any suggestions?
I can see I am not the only one to ever wish this. https://github.com/mapstruct/mapstruct/issues/1280
Thanks
I ran into the same scenario as I needed a @Context
param to be able to pass to a nested mapping function, but also wanted to use it as a source in a @Mapping
. I was able to achieve this using expression
as follows:
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);
}
To answer your second question:
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 void 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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With