Mapstruct使用详解

一、Mapstruct使用教程

Mapstruct是一个Java基于注解的Bean映射工具,它可以通过注解为不同类型的Java Bean自动生成映射器代码,以实现不同类型Java Bean之间属性的复制。下面我们来看一下如何在项目中使用Mapstruct:

1、添加依赖


<dependencies>
    <dependency>
        <groupId>org.mapstruct</groupId>
        <artifactId>mapstruct-jdk8</artifactId>
        <version>1.3.1.Final</version>
    </dependency>
</dependencies>

2、配置Maven插件

在pom.xml文件中添加Mapstruct的Maven插件,以在编译时自动生成映射器代码:


<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.0</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
                <annotationProcessorPaths>
                    <path>
                        <groupId>org.mapstruct</groupId>
                        <artifactId>mapstruct-processor</artifactId>
                        <version>1.3.1.Final</version>
                    </path>
                </annotationProcessorPaths>
            </configuration>
        </plugin>
    </plugins>
</build>

3、定义映射器接口

创建一个接口,使用MapStruct注解定义映射关系和转换规则。


@Mapper
public interface CarMapper {
    CarMapper INSTANCE = Mappers.getMapper(CarMapper.class);
    CarDTO carToCarDTO(Car car);
    List<CarDTO> carsToCarDTOs(List<Car> cars);
}

4、使用映射器接口

现在可以使用在上一步中定义的映射器接口进行转换。比如:


public class CarService {
    public CarDTO getCarById(int id) {
        Car car = carDao.getCarById(id);
        return CarMapper.INSTANCE.carToCarDTO(car);
    }
}

二、Mapstruct原理

MapStruct是通过自动生成Java映射器实现属性映射的。它的工作原理如下:

1、生成源代码

在编译时,MapStruct会扫描所有使用@Mapper注解的接口,然后自动生成Java代码来实现这些接口。这些Java代码包括源Bean和目标Bean之间属性的映射代码。

2、生成映射器实例

编译后,MapStruct会将生成的Java代码打包成一个.jar文件,然后被添加到项目的classpath中。这时,就可以使用Mappers.getMapper()静态方法获取映射器实例来实现Bean属性映射。

3、根据注解生成Mapper代码

在定义@Mapper注解时,使用source和target属性来指定映射源Bean和目标Bean。使用@Mapping注解来规定源Bean和目标Bean属性之间的映射关系。同时,MapStruct允许开发者自定义映射规则,比如类型转换等。

三、Mapstruct用法

1、使用默认规则

MapStruct具有一些默认规则,比如基本类型之间的映射,容器之间的映射等。如果源Bean和目标Bean的属性名称相同且类型相同,就无需额外的映射定义。

2、使用@Mapper注解

在过程中,可以使用@Mapper注解来定义属性映射规则。在@Mapper注解上设置componentModel属性的值为spring,可以使用@Autowired来注入Mapper。


@Mapper(componentModel = "spring")
public interface CarMapper {
    CarMapper INSTANCE = Mappers.getMapper(CarMapper.class);
    @Mapping(source = "numberOfSeats", target = "seatCount")
    CarDTO carToCarDTO(Car car);
    List<CarDTO> carsToCarDTOs(List<Car> cars);
}

3、使用@MapperConfig注解

可以在使用@Mapper注解的类上使用@MapperConfig注解设置映射器的通用配置,从而省略每个映射器的相同重复代码。


@MapperConfig(
    componentModel = "spring",
    nullValueMappingStrategy = NullValueMappingStrategy.RETURN_DEFAULT)
public interface MappingConfig {}

4、使用@Mappings注解

@Mappings注解用于集中配置常用的@Mapping注解规则,以避免在每个映射器中都重复编写单个规则。


@Mapper(componentModel = "spring")
public interface CarMapper {
    CarMapper INSTANCE = Mappers.getMapper(CarMapper.class);
    @Mappings({
      @Mapping(source = "numberOfSeats", target = "seatCount"),
      @Mapping(source = "type", target = "model"),
      @Mapping(source = "price", target = "price", numberFormat = "$#.00")
    })
    CarDTO carToCarDTO(Car car);
}

5、Spring Boot配置生命周期回调

在Spring Boot应用程序中使用MapStruct时,可以实现映射器接口上的SpringBean映射,使用@PostConstruct启动映射器。


@Mapper(componentModel = "spring")
public interface CarMapper {
    CarMapper INSTANCE = Mappers.getMapper(CarMapper.class);

    @PostConstruct
    default void init() {
        // Do Some initialization work
    }
    ...
}

四、Mapstruct设置默认值

1、使用@DefaultValue注解

可以使用@DefaultValue注解在源Bean属性为空时设置默认值。


@Mapper
public interface CarMapper {
    CarMapper INSTANCE = Mappers.getMapper(CarMapper.class);
    @Mapping(source = "numberOfSeats", target = "seatCount")
    @Mapping(source = "type", target = "model")
    @Mapping(target = "price", numberFormat = "$#.00")
    @Mapping(target = "description", defaultValue = "This car has no description.")
    CarDTO carToCarDTO(Car car);
}

2、使用@CollectionMapping注解

在@CollectionMapping注解中,通过使用@IterableMapping或者@MapMapping注解可以设置集合属性的默认值。


@Mapper
public interface CarMapper {
    CarMapper INSTANCE = Mappers.getMapper(CarMapper.class);
    @Mapping(source = "numberOfSeats", target = "seatCount")
    @IterableMapping(nullValueMappingStrategy = NullValueMappingStrategy.RETURN_DEFAULT)
    List<String> featuresToFeatureNames(List<Feature> features);
}

以上就是关于Mapstruct使用的详细讲解。它可以让我们在编写JavaBean之间复制属性时更加方便,提高了开发效率。在实际项目中使用Mapstruct,可以让我们更加专注于业务逻辑的实现。

原创文章,作者:SSLRK,如若转载,请注明出处:https://www.506064.com/n/330937.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
SSLRKSSLRK
上一篇 2025-01-16 15:46
下一篇 2025-01-16 15:46

相关推荐

  • Linux sync详解

    一、sync概述 sync是Linux中一个非常重要的命令,它可以将文件系统缓存中的内容,强制写入磁盘中。在执行sync之前,所有的文件系统更新将不会立即写入磁盘,而是先缓存在内存…

    编程 2025-04-25
  • 神经网络代码详解

    神经网络作为一种人工智能技术,被广泛应用于语音识别、图像识别、自然语言处理等领域。而神经网络的模型编写,离不开代码。本文将从多个方面详细阐述神经网络模型编写的代码技术。 一、神经网…

    编程 2025-04-25
  • nginx与apache应用开发详解

    一、概述 nginx和apache都是常见的web服务器。nginx是一个高性能的反向代理web服务器,将负载均衡和缓存集成在了一起,可以动静分离。apache是一个可扩展的web…

    编程 2025-04-25
  • git config user.name的详解

    一、为什么要使用git config user.name? git是一个非常流行的分布式版本控制系统,很多程序员都会用到它。在使用git commit提交代码时,需要记录commi…

    编程 2025-04-25
  • 详解eclipse设置

    一、安装与基础设置 1、下载eclipse并进行安装。 2、打开eclipse,选择对应的工作空间路径。 File -> Switch Workspace -> [选择…

    编程 2025-04-25
  • Java BigDecimal 精度详解

    一、基础概念 Java BigDecimal 是一个用于高精度计算的类。普通的 double 或 float 类型只能精确表示有限的数字,而对于需要高精度计算的场景,BigDeci…

    编程 2025-04-25
  • MPU6050工作原理详解

    一、什么是MPU6050 MPU6050是一种六轴惯性传感器,能够同时测量加速度和角速度。它由三个传感器组成:一个三轴加速度计和一个三轴陀螺仪。这个组合提供了非常精细的姿态解算,其…

    编程 2025-04-25
  • Python输入输出详解

    一、文件读写 Python中文件的读写操作是必不可少的基本技能之一。读写文件分别使用open()函数中的’r’和’w’参数,读取文件…

    编程 2025-04-25
  • Python安装OS库详解

    一、OS简介 OS库是Python标准库的一部分,它提供了跨平台的操作系统功能,使得Python可以进行文件操作、进程管理、环境变量读取等系统级操作。 OS库中包含了大量的文件和目…

    编程 2025-04-25
  • Linux修改文件名命令详解

    在Linux系统中,修改文件名是一个很常见的操作。Linux提供了多种方式来修改文件名,这篇文章将介绍Linux修改文件名的详细操作。 一、mv命令 mv命令是Linux下的常用命…

    编程 2025-04-25

发表回复

登录后才能评论