Java / MapStruct Java Interview questions part 2
How do you use @BeforeMapping and @AfterMapping?
These annotations let you run custom code immediately before or after MapStruct's generated mapping logic executes, without having to reimplement the whole method by hand.
@Mapper public abstract class OrderMapper { @Mapping(target = "total", ignore = true) public abstract OrderDto toDto(Order order); @AfterMapping protected void calculateTotal(Order order, @MappingTarget OrderDto dto) { dto.setTotal(order.getItems().stream() .mapToDouble(Item::getPrice).sum()); } }
@BeforeMapping methods run first and can pre-populate or validate the target before generated field copying happens; @AfterMapping methods run last, which is the common place to fill derived fields that don't map one-to-one from the source, such as a computed total.
More Related questions...