Mapstruct构造函数注入(春季)

时间:2019-04-21 21:00:58

标签: mapstruct

在mapstruct 1.3.0.Final中,我们通过构造函数进行了依赖注入。文档说:

  

生成的映射器将注入用途中定义的所有类   属性

     

(...)

     

对于抽象类或装饰器,setter注入应为   使用。

我有以下示例:

@Mapper
public abstract class VehicleMapper {

    @Autowired
    private CarMapper carMapper;
    @Autowired
    private BikeMapper bikeMapper;

    @Override
    public VehicleDTO toDto(final Vehicle source) {

        if (source instanceof Car) {
            return carMapper.toDto((Car) source);
        } else if (source instanceof Bike) {
            return bikeMapper.toDto((Bike) source);
        } else {
            throw new IllegalArgumentException();
        }
    }
    (...)

因此,在我的情况下,它应该看起来像这样({maven中定义的componentModel):

@Mapper
public abstract class VehicleMapper {

    private CarMapper carMapper;
    private BikeMapper bikeMapper;

    @Autowired
    public void setCarMapper(final CarMapper carMapper) {
        this.carMapper = carMapper;
    }

    @Autowired
    public void setBikeMapper(final BikeMapper bikeMapper) {
        this.bikeMapper = bikeMapper;
    }

    @Override
    public VehicleDTO toDto(final Vehicle source) {

        if (source instanceof Car) {
            return carMapper.toDto((Car) source);
        } else if (source instanceof Bike) {
            return bikeMapper.toDto((Bike) source);
        } else {
            throw new IllegalArgumentException();
        }
    }
    (...)

问题:
因此,无法通过构造函数注入carMapperbikeMapper吗? injectionStrategy = CONSTRUCTOR仅适用于在@Mapper(uses = {})中声明的类吗?

1 个答案:

答案 0 :(得分:0)

我认为injectionStrategy = CONSTRUCTOR在带有@Mapper批注的接口上起作用。我认为它不适用于抽象类。我确定当您定义自己的字段(实例变量)时,它将无法正常工作。 MapStruct如何知道哪些用户定义的字段要在构造函数中初始化?