如何将spring bean注入(custructor)到Mapstruct的抽象映射器中? [英] How to inject(custructor) a spring bean into abstract mapper of Mapstruct?

查看:39
本文介绍了如何将spring bean注入(custructor)到Mapstruct的抽象映射器中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下映射器类,我想在其中使用 CounterService.我正在尝试构造函数注入,但这不起作用并且 null 正在打印.

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

}

通过mapStruct

@Component
public class CarMapperImpl extends CarMapper{

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

如果我使用 @AutoWired 使用字段注入,那么它工作正常.这意味着 Spring 不支持 abstract 类的构造函数注入.是不是因为abstract类不能直接实例化,需要一个子类来实例化?
mapStruct 有什么办法可以在实现类中创建一个构造函数:

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.

推荐答案

这与 Spring 无关.MapStruct 团队经过深思熟虑决定不使用超级构造函数.

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

你可以做的是使用 setter 注入.

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

}

这篇关于如何将spring bean注入(custructor)到Mapstruct的抽象映射器中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆