Java / MapStruct Java Interview questions part 2
How do you retrieve a mapper instance without Spring?
With the default componentModel, MapStruct generates a static INSTANCE field pattern is optional, but the standard approach is calling the Mappers factory class, which looks up the generated implementation by naming convention.
@Mapper public interface CarMapper { CarMapper INSTANCE = Mappers.getMapper(CarMapper.class); CarDto toDto(Car car); } CarDto dto = CarMapper.INSTANCE.toDto(car);
Mappers.getMapper simply instantiates the generated CarMapperImpl class; it does not use reflection to build the mapping logic, only to locate the already-generated implementation class. Declaring the constant as INSTANCE on the interface itself is just a convention, not a requirement of the framework.
More Related questions...