本章节内容对应官网4. Retrieving a mapper
当我们有了实体类,也写好了映射关系的Mapper后,在代码中我们如何获取这个Mapper然后调用里面的方法呢?
本章节将介绍相关内容。
1.没有依赖注入的情况下,普通方式使用
当不适用依赖注入的框架时(比如spring),可以通过org.mapstruct.factory.Mappers类来获取一个mapper实例。具体用法如下:
- @Mapper
- public interface CarMapper {
- CarMapper INSTANCE = Mappers.getMapper( CarMapper.class );//[1]
- CarDto carToCarDto(Car car);
- }
-
- public class Test {
- public static void main(String[] args) {
- Car car = new Car( "Morris", 5);
- CarDto carDto = CarMapper.INSTANCE.carToCarDto(car);//[2]
- }
- }
[1]处通过Mapper.getMapper获取mapper实例,然后再代码中[2]处获取就可以那这个mapper来调用mapper中的方法了。
2.通过依赖注入的方式
当我们使用依赖注入的方式,例如使用了spring框架等,我们就可以通过注入的方式获取到mapper实例,然后调用mapper中的方法。如下:
- @Mapper(componentModel = MappingConstants.ComponentModel.CDI) //[1]
- public interface CarMapper {
- CarDto carToCarDto(Car car);
- }
-
- public class Test {
- @Inject
- private CarMapper mapper;//[2]
-
- public void m1(){
- Car car = new Car( "Morris", 5);
- CarDto carDto = mapper.carToCarDto(car);
- }
- }
另外里面还有其他多种形式,可以看一下截图:

3.关于依赖注入的策略[4.3. Injection strategy]
当采用上面依赖注入的方式时,可以同过字段的形式注入,也可以通过构造函数进行注入。要用哪种注入方式,在@Mapper或者@MapperConfig中指定即可。如下:

到此,本章节结束。谢谢!