簡體   English   中英

mapstruct 在另一個測試中使用 mapper 返回 null

[英]mapstruct using mapper inside another return null in test

我正在使用 mapstruct 生成映射器。 當我在生成的代碼中看到它在Mymapper中自動裝配MainMapper但在調試時它顯示 myMapper 為空。 當我更改生成的代碼時

@Autowired MyMapper myMapper

和:

MyMapper myMapper=Mappers.getMaper(MyMapper.class)

,它正在工作,但這不是我想要的。 我希望它像框架預期的那樣自動生成。 nb: MainMapper使用MyMapper ,而MyMapper使用Mapper2

主映射器:

@Mapper(componentModel = "spring", 
    unmappedTargetPolicy = ReportingPolicy.IGNORE, 
    uses = MyMapper.class ,
    nullValueMappingStrategy = NullValueMappingStrategy.RETURN_NULL)
public interface MainMapper {

    @Mappings({ @Mapping(target = "year", source = "Period.year") })
    Resource toResource(MyObject myObject);

    @Mapping(target = "Period.year", source = "year")
    MyObject toModel(Resource resource);
}

我的地圖:

@Mapper(componentModel = "spring", 
    unmappedTargetPolicy = ReportingPolicy.IGNORE,
    uses = Mapper2.class,
    nullValueMappingStrategy = NullValueMappingStrategy.RETURN_NULL)
public interface MyMapper {

    RequestResource toResource(Request request);

    Request toModel(RequestResource requestResource);
}

任何幫助表示贊賞。

我自己也遇到過這個問題。 我能夠通過使用默認組件模型來解決它。 這是我的情況:

  1. 我正在使用componentModel = "spring"
  2. 我試圖在單獨的 Spring 組件中使用我的映射器。
  3. @Autowired運行測試時域引用映射器賦予NullPointerException異常的。

如果這聽起來像是發生在您身上的事情,您必須使用componentModel = "default" 我想使用 Spring 組件模型; 但是,在用頭撞牆一個小時后,我決定嘗試默認組件模型。

將我的映射器更改為默認組件模型並替換@Autowired字段后,我不再收到可怕的NullPointerException !!

工作代碼:

@Component
public class Mapper implements MapperTranslator<Output, Input> {
    private final MappingVisitor mappingVisitor = Mappers.getMapper(MappingVisitor.class);
    private final MappingDefault mappingDefault = Mappers.getMapper(MappingDefault.class);

    @Override
    public Output translate(Input source) {
        if (source instanceof InputType1) {
            return ((InputType1)source).acceptAndMap(mappingVisitor);
        }
        else if (source instanceof InputType2) {
            return ((InputType2)source).acceptAndMap(mappingVisitor);
        }

        // default
        return mappingDefault.translate(source);
    }
}

我也在使用spring組件模型,並在故障排除時發現了這個 SO 線程。 對我有用的是,在我的測試類中,我需要添加這些字段,而不是直接在我的測試方法中引用映射器類。

@Autowired
private final MyCustomMapper pMapper = Mappers.getMapper(MyCustomMapper.class);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM