How to inject(custructor) a spring bean into abstract mapper of Mapstruct?

北慕城南 提交于 2021-02-10 18:37:57

问题


I am having below mapper class in which I want to use CounterService. I am trying constructor injection but that's not working and null is printing.

@Mapper(componentModel = "spring", uses = CounterService.class, injectionStrategy = InjectionStrategy.CONSTRUCTOR)
public abstract class CarMapper {

    private CounterService counterService;

    public CarMapper(CounterService counterService) {
       this.counterService = counterService;
    }

    public abstract Car dtoToEntity(CarDto carDto);

    public CarDto entityToDto(Car car) {
        System.out.println(counterService)
        //....
        return carDto;
    }

}

Implementation class by mapStruct

@Component
public class CarMapperImpl extends CarMapper{

  @Override
  public Car dtoToEntity(CarDto carDto){
    //...
  }
}

If I use field injection using @AutoWired, that way it works fine. It means Spring doesn't support the constructor injection of abstract class. Is it because abstract class can't be instantiated directly and require a subclass to instantiate?
Is there any way mapStruct can create a constructor inside the implementation class as:

  public CarMapperImpl(CounterService counterService){
    super(counterService);
  }

That way, constructor injection should work.


回答1:


This has nothing to do with Spring. It was a deliberate decision done by the MapStruct team to not use super constructors.

What you can do though is to use setter injection.

@Mapper(componentModel = "spring", uses = CounterService.class, injectionStrategy = InjectionStrategy.CONSTRUCTOR)
public abstract class CarMapper {

    private CounterService counterService;

    public abstract Car dtoToEntity(CarDto carDto);

    public CarDto entityToDto(Car car) {
        System.out.println(counterService)
        //....
        return carDto;
    }

    @Autowired
    public void setCounterService(CounterService counterService) {
        this.counterService = counterService;
    }

}


来源:https://stackoverflow.com/questions/58451618/how-to-injectcustructor-a-spring-bean-into-abstract-mapper-of-mapstruct

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!