簡體   English   中英

在另一個帶有 mapstruct 的自定義映射器中使用自定義映射器(默認方法)

[英]Use a custom mapper inside another custom mapper with mapstruct (in default method)

我想在 MapperA 的默認方法中使用 MapperB

類似於這個問題: How can I use another mapping from different class in mapstruct

然而 afaik 這個問題並沒有要求“自定義映射器”,即作為自己的界面存在的映射器。

我怎么能那樣做?

我有一個 MapperA 接口和一個 MapperB 接口

我將如何在 MapperA 中使用 MapperB?

像這樣:

@Mapper
public interface MapperA {

    @Autowired
    MapperB mapperB; 

    default ArrayList<AudioDto> audiosToDto(List<Audio> audios, ApplicationUser loggedInUser) {
    Stream<AudioDto> audiosStream = audios.stream().map((Audio audio) -> mapperB.audioToAudioDto(audio, loggedInUser));
    return audiosStream.collect(Collectors.toCollection(ArrayList::new));
}

上面的代碼不起作用。 現在我嘗試添加 @Component(to MapperA & MapperB) 以便能夠自動裝配它,但它仍然給我:

@Autowired <- 不推薦字段注入

映射器B映射器B; <- 變量“audioMapper”可能尚未初始化

即使在 maven-cleaning 項目以擺脫 MapperAImpl 之后。

您應該將MapperA定義為抽象 class 而不是接口,並使用 setter 注入來注入MapperB ,如下所示:

@Mapper(componentModel="spring")
public abstract class MapperA {

    private MapperB mapperB; 

    @Autowired
    public final void setMapperB(MapperB mapperB) {
        this.mapperB = mapperB;
    }

    public ArrayList<AudioDto> audiosToDto(List<Audio> audios, ApplicationUser loggedInUser) {
        Stream<AudioDto> audiosStream = audios.stream().map((Audio audio) -> mapperB.audioToAudioDto(audio, loggedInUser));
        return audiosStream.collect(Collectors.toCollection(ArrayList::new));
    }
}

暫無
暫無

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

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