0

Is there a way to autowire all mappers written with Mapstruct in Spring just like we used to do with the Spring Converter interface and calling one toEntity(or convert or any other name)? In spring, it is easy because they all implement the same functional interface and by making it inherit from another interface we can determine the right converter in the runtime like below:

import org.springframework.core.convert.converter.Converter;

public interface CustomConverter<S extends ..., T extends ...> extends Covnerter<S,T>{

boolean supports(Class clazz);
}

And then injecting it would be easy:

@Autowire
private final List<CustomConverter> myConverters;

and by calling supports we would determine the right kind of converter and then call convert against it. I had something like this in mind:

@Mapper
public interface MyMapper extends CustomMapper<MyEntity, MyDto>{
MyMapper INSTANCE = Mappers.getMapper(MyMapper.class);

MyEntity toEntity(MyDto dto);

default boolean supports(Class clazz) {
return MyDto.class.isAssignableFrom(clazz);
}

And

public interface CustomMapper<T extends ..., S extends ...> {

boolean supports(Class clazz);
T toEntity(S dto);
}

This does not work though. Do you have any suggestions here? I might have misunderstood this all together...Thanks.

BlackLog
  • 301
  • 1
  • 5
  • 17

1 Answers1

0

Checkout: https://github.com/mapstruct/mapstruct-spring-extensions

The author made and adapter based on a discusion in this SO issue.

A non spring based solution can be found here. Although you need to write your own annotation processor.

Sjaak
  • 3,602
  • 17
  • 29