MapStruct-Plus 使用教程
项目介绍
MapStruct-Plus 是一个基于 MapStruct 的增强库,旨在简化 Java 对象之间的映射配置。它通过与 Lombok 注解结合,提供了更便捷的映射功能,同时保持与 MapStruct 的完全兼容性。MapStruct-Plus 使用 Apache-2.0 许可证,是一个开源项目,可以在 GitHub 上找到其源代码和相关文档。
项目快速启动
添加依赖
首先,在您的 Spring Boot 项目的 pom.xml
文件中添加 MapStruct-Plus 和 Lombok 的依赖:
<properties>
<java.version>19</java.version>
<mapstruct-plus.version>1.3.5</mapstruct-plus.version>
<lombok.version>1.18.30</lombok.version>
</properties>
<dependencies>
<dependency>
<groupId>io.github.linpeilie</groupId>
<artifactId>mapstruct-plus</artifactId>
<version>${mapstruct-plus.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
实体类
定义需要映射的实体类,并使用 Lombok 注解简化代码:
import lombok.Data;
@Data
public class Source {
private String name;
private int age;
}
@Data
public class Target {
private String name;
private int age;
}
映射接口
创建一个映射接口,并使用 MapStruct-Plus 注解:
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.factory.Mappers;
@Mapper
public interface SourceTargetMapper {
SourceTargetMapper INSTANCE = Mappers.getMapper(SourceTargetMapper.class);
@Mapping(source = "name", target = "name")
@Mapping(source = "age", target = "age")
Target sourceToTarget(Source source);
}
测试类
编写测试类来验证映射是否正确:
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class SourceTargetMapperTest {
@Test
public void testMapping() {
Source source = new Source();
source.setName("John");
source.setAge(30);
Target target = SourceTargetMapper.INSTANCE.sourceToTarget(source);
assertEquals("John", target.getName());
assertEquals(30, target.getAge());
}
}
应用案例和最佳实践
复杂对象映射
MapStruct-Plus 不仅支持简单对象的映射,还支持复杂对象的映射。例如,如果 Source
类中包含一个嵌套对象,可以通过定义相应的映射方法来处理:
@Data
public class Source {
private String name;
private int age;
private Address address;
}
@Data
public class Address {
private String street;
private String city;
}
@Data
public class Target {
private String name;
private int age;
private Address address;
}
@Mapper
public interface SourceTargetMapper {
SourceTargetMapper INSTANCE = Mappers.getMapper(SourceTargetMapper.class);
@Mapping(source = "name", target = "name")
@Mapping(source = "age", target = "age")
@Mapping(source = "address", target = "address")
Target sourceToTarget(Source source);
}
自定义映射逻辑
如果需要自定义映射逻辑,可以在映射接口中定义自定义方法:
@Mapper
public interface SourceTargetMapper {
SourceTargetMapper INSTANCE = Mappers.getMapper(SourceTargetMapper.class);
@Mapping(source = "name", target = "name")