0

I want to use MapperB inside MapperA's default method

Similar to this question: How can I use another mapping from different class in mapstruct

However afaik this question did not ask for 'custom mappers', i.e. mappers that exist as their own interface.

How would I be able to do that?

I have an interface of MapperA and an interface of MapperB

How would I use the MapperB inside MapperA?

like so:

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

The above code didn't work. Now I tried adding @Component(to MapperA & MapperB) to be able to autowire it, but it's still giving me:

@Autowired <- Field injection is not recommended

MapperB mapperB; <- Variable 'audioMapper' might not have been initialized

even after maven-cleaning the project to get rid of the MapperAImpl.

Chef Lax
  • 89
  • 2
  • 10

1 Answers1

0

You should define the MapperA as an abstract class instead of an interface, and use setter injection to inject MapperB as follows:

@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));
    }
}
Toni
  • 3,296
  • 2
  • 13
  • 34