防止Mapstruct覆盖方法

时间:2020-07-03 10:40:24

标签: java spring mapstruct

是否有一种方法可以防止mapstruct覆盖我在mapper类中提供的实现的特定方法?

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

  • 我尝试制作方法final,它不起作用
  • 我曾尝试在qualifiedByName中使用@Mapping,但无法正常工作

我的映射器类如下:

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

1 个答案:

答案 0 :(得分:0)

您必须在实现中使用@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);