Ask Question

How can I access a Spring Bean inside my MapStruct Mapper?

What is the preferable way to access some Spring Service or another Bean inside of my MapStruct Mapper? (e.g. in the @AfterMapping method)

JavamapstructSpring

7607 views

Author´s Dominik Sumer image

Dominik Sumer

Last edited on
Author´s Lorenz Leutgeb image
Note that MapStruct is not specific to Spring. It can also be used with CDI, Spring and JSR330. See the docs on dependency injection in the MapStruct Reference Manual and the componentModel configuration option. The question you are asking is relevant independently of the component model used.
 (edited)
2

1 Answer available

Best answer

I think a good solution would be to provide the bean instance with the @Context parameter from MapStruct. Usually when you're calling your MapStruct mapper, you're operating inside a Spring Bean anyway, therefore you could just pass the desired bean to your mapping function. Then you'll have access to it in submethods of you MapStruct Mapper.

As an example, this would be a part of the mapper code:

...
import org.mapstruct.Context;

interface MyMapper {
  Dto mapEntityToDto(Entity entity, @Context EntityInfoService entityInfoService);
}

And here you're calling the Method of the mapper inside a Spring Service:

...

@Service
public class MyService {
  private final EntityRepository entityRepository;
  private final EntityInfoService entityInfoService;
  private final MyMapper myMapper;

  // ... imagine constructor where you autowire your beans

  public Dto getDto() {
    Entity myEntity = entityRepository.getEntity();

    return myMapper.mapEntityToDto(myEntity, entityInfoService);
  }
}

Cheers!

❤️
1