I've created some mapstruct mapper annotated with spring constructor injection. I know in the test I can autowire the mapper with springboottest
, but it seems very heavy and the loading speed is very slow. Can I get the mapper without initializing the spring context? Is this good practice?
Asked
Active
Viewed 368 times
1

LunaticJape
- 1,446
- 4
- 21
- 39
1 Answers
1
You can always get a mapper by means of Mappers.getMapper(MapperClass.class)
. However, the problem arises when that mapper uses other mappers.
When using other mappers (@Mapper.uses
) you might also want to use (@Mapper.injectionStrategy
) and use constructor injection. Since mappers are stateless by design, you could write some reflective code yourself to construct a mapper with all its dependent uses
mappers.

Sjaak
- 3,602
- 17
- 29
-
Do you mean I have to instantiate manually the mapper including any injection chain? – LunaticJape Apr 28 '20 at 14:52
-
Yes. If you don't use frameworks during test to arrange injection, you need to use reflection (that is also what `Mappers.getMapper` does. I would recommend to do this only in unit test. For testing, checkout https://stackoverflow.com/questions/61398218/how-to-efficiently-test-mapstruct-spring-mapper as well. – Sjaak Apr 28 '20 at 18:48
-
oops.. Sorry, wrong stuff under my paste button.. Here's the proper link: https://stackoverflow.com/questions/60986556/how-to-tests-and-mock-mapstruct-converter – Sjaak Apr 28 '20 at 19:41