跳转至

关于MapStruct

约 512 个字 131 行代码 预计阅读时间 3 分钟

MapStruct 是一个用于对象映射的 Java 注解处理器,它能够在编译期根据接口定义生成类型安全的映射实现类,避免运行时使用反射,因此性能较高。常见的使用场景包括 EntityDTOVO 之间的转换。

依赖引入

在 Maven 项目中使用 MapStruct 时,需要同时引入运行时依赖和编译期注解处理器,并且两者版本必须保持一致。下面的示例使用的是当前较新的稳定版本 1.6.3

XML
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<properties>
    <java.version>17</java.version>
    <org.mapstruct.version>1.6.3</org.mapstruct.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.mapstruct</groupId>
        <artifactId>mapstruct</artifactId>
        <version>${org.mapstruct.version}</version>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.13.0</version>
            <configuration>
                <source>${java.version}</source>
                <target>${java.version}</target>
                <annotationProcessorPaths>
                    <path>
                        <groupId>org.mapstruct</groupId>
                        <artifactId>mapstruct-processor</artifactId>
                        <version>${org.mapstruct.version}</version>
                    </path>
                </annotationProcessorPaths>
            </configuration>
        </plugin>
    </plugins>
</build>

基本使用

假设存在如下源对象和目标对象:

Java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
public class User {
    private Long id;
    private String name;
    private String email;
    // getter / setter ...
}

public class UserDto {
    private Long id;
    private String username;
    private String email;
    // getter / setter ...
}

定义 Mapper 接口:

Java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.factory.Mappers;

@Mapper
public interface UserMapper {

    UserMapper INSTANCE = Mappers.getMapper(UserMapper.class);

    @Mapping(source = "name", target = "username")
    UserDto toDto(User user);
}

编译完成后,MapStruct 会自动生成 UserMapperImpl 实现类。使用方式如下:

Java
1
2
3
4
5
6
User user = new User();
user.setId(1L);
user.setName("张三");
user.setEmail("zhangsan@example.com");

UserDto dto = UserMapper.INSTANCE.toDto(user);

字段名不同的映射

当多个字段名不一致时,可以使用 @Mappings 包裹多个 @Mapping

Java
1
2
3
4
5
@Mappings({
    @Mapping(source = "name", target = "username"),
    @Mapping(source = "phoneNumber", target = "mobile")
})
UserDto toDto(User user);

忽略字段与使用常量

如果目标对象中的某些字段不需要映射,或者需要赋予固定值,可以按下面的方式配置:

Java
1
2
3
4
5
6
@Mappings({
    @Mapping(source = "name", target = "username"),
    @Mapping(target = "password", ignore = true),
    @Mapping(target = "status", constant = "ACTIVE")
})
UserDto toDto(User user);

集合映射

MapStruct 可以直接对集合进行整体映射,内部会自动遍历元素:

Java
1
List<UserDto> toDtoList(List<User> users);

Spring Boot 集成

在 Spring Boot 项目中,通常希望 MapStruct 生成的实现类被 Spring 管理。可以在 @Mapper 注解中指定组件模型:

Java
1
2
3
4
5
6
7
import org.mapstruct.Mapper;
import org.mapstruct.MappingConstants;

@Mapper(componentModel = MappingConstants.ComponentModel.SPRING)
public interface UserMapper {
    UserDto toDto(User user);
}

然后在服务中直接注入使用:

Java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    public UserDto getUserDto(Long id) {
        User user = ...;
        return userMapper.toDto(user);
    }
}

也可以在 maven-compiler-plugin 中通过编译参数全局设置默认组件模型,这样所有 @Mapper 都会默认生成 Spring Bean:

XML
1
2
3
<compilerArgs>
    <arg>-Amapstruct.defaultComponentModel=spring</arg>
</compilerArgs>

与 Lombok 一起使用

当项目中同时使用 Lombok 和 MapStruct 时,两者都需要注解处理器,处理顺序很重要。推荐顺序为:Lombok → lombok-mapstruct-binding → MapStruct:

XML
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<properties>
    <lombok.version>1.18.36</lombok.version>
    <lombok-mapstruct-binding.version>0.2.0</lombok-mapstruct-binding.version>
    <org.mapstruct.version>1.6.3</org.mapstruct.version>
</properties>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.13.0</version>
            <configuration>
                <annotationProcessorPaths>
                    <path>
                        <groupId>org.projectlombok</groupId>
                        <artifactId>lombok</artifactId>
                        <version>${lombok.version}</version>
                    </path>
                    <path>
                        <groupId>org.projectlombok</groupId>
                        <artifactId>lombok-mapstruct-binding</artifactId>
                        <version>${lombok-mapstruct-binding.version}</version>
                    </path>
                    <path>
                        <groupId>org.mapstruct</groupId>
                        <artifactId>mapstruct-processor</artifactId>
                        <version>${org.mapstruct.version}</version>
                    </path>
                </annotationProcessorPaths>
            </configuration>
        </plugin>
    </plugins>
</build>

常见问题

问题 说明
编译后没有生成实现类 检查 mapstruct-processor 是否在 annotationProcessorPaths 中,且版本与 mapstruct 一致
字段名相同但无法映射 检查是否缺少 getter/setter,或者字段被声明为 static / transient
不想看到未映射字段警告 @Mapper 上添加 unmappedTargetPolicy = ReportingPolicy.IGNORE
与 Lombok 联用报错 确认注解处理器顺序正确,并引入 lombok-mapstruct-binding