I try to autowire my mapstruct mapper:
@Mapper(uses = { A.class, B.class, C.class }) public interface WindowDtoMapper { WindowDtoMapper INSTANCE = Mappers.getMapper(WindowDtoMapper.class); DetailedDto mapToDetailedDto(Window window); ReadDto mapToReadDto(Window window); }
This works:
return WindowDtoMapper.INSTANCE.mapToDetailedDto(window)
But WHY I can’t use:
@RequiredArgsConstructor public class AAA(){ private final WindowDtoMapper windowDtoMapper; windowDtoMapper.mapToDetailedDto(window) }
I get the following error:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type ‘pl.comp.window.application.mapper.WindowDtoMapper’ available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {} at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1717) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1273)
Maybe I should stay with the first working solution? Is it bad solution or not?
Advertisement
Answer
By default, MapStruct generates ordinary Java classes, and that’s all. Spring has no way of knowing that you want these to be beans.
As described in the MapStruct documentation, you can use @Mapper(componentModel = "spring")
to have MapStruct put @Component
on the classes it creates (you’ll need to make sure that the package with the mappers is getting component-scanned).