I need to inject a spring service class in the generated mapper implementation, so that I can use it via
@Mapping(target="x", expression="java(myservice.findById(id))")"
Is this applicable in Mapstruct-1.0?
As commented by brettanomyces, the service won't be injected if it is not used in mapping operations other than expressions.
The only way I found to this is :
I'm using CDI but it should be the samel with Spring :
@Mapper( unmappedTargetPolicy = org.mapstruct.ReportingPolicy.IGNORE, componentModel = "spring", uses = { // My other mappers... }) public abstract class MyMapper { @Autowired protected MyService myService; @Mappings({ @Mapping(target="x", expression="java(myservice.findById(obj.getId())))") }) public abstract Dto myMappingMethod(Object obj); }
It should be possible if you declare Spring as the component model and add a reference to the type of myservice
:
@Mapper(componentModel="spring", uses=MyService.class) public interface MyMapper { ... }
That mechanism is meant for providing access to other mapping methods to be called by generated code, but you should be able to use them in the expression that way, too. Just make sure you use the correct name of the generated field with the service reference.
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