💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
**1. 映射类** ```java /** * 映射类可以用接口也可以用抽象类,这里我想用抽象类来演示 */ @Mapper public abstract class BeforeWithAfterMapper { public static BeforeWithAfterMapper INSTANCE = Mappers.getMapper(BeforeWithAfterMapper.class); /** * 映射前执行的方法 */ @BeforeMapping protected void beforeMapping() { System.out.println("映射前执行的方法!"); } @Mapping(source = "carId", target = "carDtoId") @Mapping(source = "carName", target = "carDtoName") public abstract CarDto toDto(Car source1); /** * 完成映射后执行的方法 */ @AfterMapping protected void afterMapping() { System.out.println("完成映射后执行的方法!"); } } ``` **2. 测试** ```java @Test public void testBeforeWithAfterMapper() { Car car = new Car(); car.setCarId(1001); car.setCarName("红旗"); CarDto carDto = BeforeWithAfterMapper.INSTANCE.toDto(car); System.out.println(carDto); } ``` 控制台打印的顺序如下,可见被注解`@BeforeMapping`和`@AfterMapping`标注的方法先后被执行了。 ``` 映射前执行的方法! 完成映射后执行的方法! CarDto(carDtoId=1001, carDtoName=红旗) ``` **3. 查看MapStruct编译后的代码** ```java public class BeforeWithAfterMapperImpl extends BeforeWithAfterMapper { public BeforeWithAfterMapperImpl() { } public CarDto toDto(Car source1) { this.beforeMapping(); if (source1 == null) { return null; } else { CarDto carDto = new CarDto(); carDto.setCarDtoId(source1.getCarId()); carDto.setCarDtoName(source1.getCarName()); this.afterMapping(); return carDto; } } } ```