![](/img/trans.png)
[英]How to use a mapper in another mapper using Mapstruct and Kotlin?
[英]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);
}
任何幫助表示贊賞。
我自己也遇到過這個問題。 我能夠通過使用默認組件模型來解決它。 這是我的情況:
componentModel = "spring"
。@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.