[英]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.