Java / MapStruct Java Interview questions
🔹 Basic Questions
- What is MapStruct?
MapStruct is a Java annotation processor that generates type-safe, performant, and boilerplate-free mapping code between Java beans at compile time. - How does MapStruct differ from other mapping frameworks like ModelMapper or Dozer?
Performance, type safety, and no runtime dependency. - What are the advantages of using MapStruct?
Compile-time mapping, better performance, type-safety, easy customization. - How do you define a mapper in MapStruct?
@Mapper public interface CarMapper { CarMapper INSTANCE = Mappers.getMapper(CarMapper.class); CarDto carToCarDto(Car car); }
- What is the role of the
@Mapper
annotation?
It marks an interface or abstract class as a MapStruct mapper, triggering code generation.
🔹 Intermediate Questions
- How do you map fields with different names?
@Mapping(source = "carName", target = "name")
- How do you ignore a field in MapStruct?
@Mapping(target = "someField", ignore = true)
- How do you map nested objects or collections?
Define a mapper for the nested type or let MapStruct generate them automatically.@Mapping(source = "engine.type", target = "engineType")
- How to use
@MappingTarget
?void updateCarFromDto(CarDto dto, @MappingTarget Car car);
- What is the use of
@InheritInverseConfiguration
?
Reverses the mapping logic from an existing method to avoid duplication.
🔹 Advanced Questions
- How to handle custom logic or transformations?
@Mapping(target = "price", expression = "java(convertPrice(car.getPrice()))")
- What is
@AfterMapping
and@BeforeMapping
?Hook methods to execute logic before or after mapping.
@AfterMapping void enrichCar(@MappingTarget CarDto dto) { dto.setFullName(dto.getBrand() + " " + dto.getModel()); }
- How do you map enums with MapStruct?
By default, same-name enums are mapped automatically. Use@ValueMapping
for custom behavior. - How does MapStruct handle null values?
@Mapper(nullValueMappingStrategy = NullValueMappingStrategy.RETURN_DEFAULT)
- Can you use dependency injection with MapStruct?
@Mapper(componentModel = "spring")
🔹 Real-world / Scenario-Based
- In a large project, how do you organize your mappers?
Group by domain/module, use composition, and define a central@MapperConfig
. - How do you handle circular dependencies?
Avoid cycles in DTOs or use@Context
and lifecycle methods carefully. - How do you write unit tests for MapStruct mappers?
Use JUnit to assert values from mapper method outputs. - How do you map using other services?
Inject services with@Context
or use custom expressions/methods. - How do you debug MapStruct-generated code?
Inspect generated code undertarget/generated-sources/annotations
.