【问题标题】:Prevent Mapstruct from overriding a method防止 Mapstruct 覆盖方法
【发布时间】:2020-07-03 19:31:48
【问题描述】:

有没有办法防止mapstruct 覆盖我在映射器类中提供了实现的特定方法?

我有一个方法entityDTOToVehicle,我在我的映射器类EntityMapper 中提供了一个实现,当为这个类生成映射时,mapstruct 忽略提供的实现并用它自己的实现覆盖我的实现。

  • 试过final的方法,不行
  • 我尝试在@Mapping 中使用qualifiedByName,它不起作用

我的映射器类如下所示:

public abstract class EntityMapper {

    public static final EntityMapper INSTANCE = Mappers.getMapper(EntityMapper.class);
    
    protected final Vehicle EntityDTOToVehicle(EntityDTO EntityDTO) {
        Vehicle vehicle = new Vehicle();

        //My Implementation Here

        return vehicle;
    }

    @Mapping(target = "vehicle.property1",  source = "vehicleProperty1")
    @Mapping(target = "vehicle.property2",  source = "vehicleProperty2")
    public abstract Entity map(EntityDTO dto);
}

Mapstruct 然后生成一个这样的实现:

@Component
public class EntityMapperImpl extends EntityMapper {

    @Override
    public Entity map(EntityDTO dto) {
        if ( dto == null ) {
            return null;
        }

        Entity entity = new Entity();
        .
        .
        .
        entity.setTransport( entityDTOToVehicle( dto ) );

        return entity;
    }

     /** 
     * This is the method I'd like to prevent mapstruct from overriding  */
    protected Vehicle entityDTOToVehicle(EntityDTO entityDTO) {
        Vehicle vehicle = new Vehicle();

        //Mapstruct's Implementation

        return vehicle;
    }
}

【问题讨论】:

    标签: java spring mapstruct


    【解决方案1】:

    你必须在你的实现中使用@Named

    @Named(value = "mappingName")
    protected Vehicle EntityDTOToVehicle(EntityDTO EntityDTO) {
        Vehicle vehicle = new Vehicle();
    
        //My Implementation Here
    
        return vehicle;
    }
    

    然后将其附加到抽象映射器:

    @Mappings(value ={
        @Mapping(target = "vehicle.property1",  source = "vehicleProperty1")
        @Mapping(target = "vehicle.property2",  source = "vehicleProperty2")
        @Mapping(source = "fieldWithVehiclePropChangeItToYours", target = "transport", qualifiedByName = "mappingName"),
    }
    public abstract Entity map(EntityDTO dto);
    

    【讨论】:

      猜你喜欢
      • 2021-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-04
      • 1970-01-01
      • 2014-03-14
      • 1970-01-01
      • 2018-06-27
      相关资源
      最近更新 更多