Mapstruct - How can I inject a spring dependency in the Generated Mapper class

后端 未结 5 739
慢半拍i
慢半拍i 2020-12-05 17:52

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(myservi         


        
5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-05 18:29

    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 :

    • Transform my mapper interface into an abstract class
    • Inject the service in the abstract class
    • Make it protected so the "implementation" of the abstract class has access

    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);
    
    }
    

提交回复
热议问题