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

后端 未结 5 731
慢半拍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:50

    I am using Mapstruct 1.3.1 and I have found this problem is easy to solve using a decorator.

    Example:

    @Mapper(unmappedTargetPolicy = org.mapstruct.ReportingPolicy.IGNORE,
     componentModel = "spring")
    @DecoratedWith(FooMapperDecorator.class)
    public interface FooMapper {
    
        FooDTO map(Foo foo);
    }
    
    public abstract class FooMapperDecorator implements FooMapper{
    
        @Autowired
        @Qualifier("delegate")
        private FooMapper delegate;
    
        @Autowired
        private MyBean myBean;
    
        @Override
        public FooDTO map(Foo foo) {
    
            FooDTO fooDTO = delegate.map(foo);
    
            fooDTO.setBar(myBean.getBar(foo.getBarId());
    
            return fooDTO;
        }
    }
    

    Mapstruct will generate 2 classes and mark the FooMapper that extends FooMapperDecorator as the @Primary bean.

提交回复
热议问题