Java / MapStruct Java Interview questions part 2
How do you inject dependencies into a MapStruct mapper?
Because a pure interface can't hold state, dependency injection into a mapper requires declaring it as an abstract class instead, so you can add an injected field or constructor alongside the abstract mapping methods.
@Mapper(componentModel = "spring") public abstract class PriceMapper { @Autowired protected ExchangeRateService exchangeRateService; @Mapping(target = "priceUsd", expression = "java(exchangeRateService.toUsd(product.getPrice()))") public abstract ProductDto toDto(Product product); }
MapStruct leaves the injected field alone and simply generates the mapping methods around it, so the dependency behaves like any Spring-managed field on the generated implementation class, which itself becomes a Spring bean.
More Related questions...