SpringBoot使用MapStruct生成映射代碼的示例詳解
定義
MapStruct 是一個用于 Java 的代碼生成器,專門用于生成類型安全的 bean 映射代碼。它通過注解處理器在編譯時生成映射代碼,從而避免了運行時的性能開銷和潛在的錯誤。
MapStruct 的主要目標是簡化和加速 Java 對象之間的轉換,特別是當這些對象具有相似的結構時。
相關概念
Mapper接口 Mapper 接口定義了對象之間的映射方法。你可以通過在接口上使用 @Mapper
注解來標記這個接口是一個映射器。MapStruct 會在編譯時生成這個接口的實現類。Mapping注解 @Mapping 注解用于定義源對象和目標對象之間的字段映射關系。你可以在 Mapper
接口的方法上使用這個注解來指定具體的映射規(guī)則。Mappings注解 @Mappings 注解是 @Mapping 注解的容器,用于定義多個字段映射。Component Model通過 componentModel 屬性,你可以指定生成的 Mapper 實現類的組件模型,例如Spring、CDI 或默認的無組件模型。
使用示例
- 定義源對象和目標對象
public class Source {
private String name;
private int age;
private String address;
// getters and setters
}
public class Target {
private String fullName;
private int age;
private String location;
// getters and setters
}
- 定義Mapper接口
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 = "fullName")
@Mapping(source = "address", target = "location")
Target sourceToTarget(Source source);
@Mapping(source = "fullName", target = "name")
@Mapping(source = "location", target = "address")
Source targetToSource(Target target);
}
或者,可以使用 @Mappings 注解來包含多個 @Mapping 注解。@Mappings 注解是 @Mapping 注解的容器,用于定義多個字段映射。
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Mappings;
import org.mapstruct.factory.Mappers;
@Mapper
public interface SourceTargetMapper {
SourceTargetMapper INSTANCE = Mappers.getMapper(SourceTargetMapper.class);
@Mappings({
@Mapping(source = "name", target = "fullName"),
@Mapping(source = "address", target = "location")
})
Target sourceToTarget(Source source);
@Mappings({
@Mapping(source = "fullName", target = "name"),
@Mapping(source = "location", target = "address")
})
Source targetToSource(Target target);
}
- 主方法
public class Main {
public static void main(String[] args) {
Source source = new Source();
source.setName("John Doe");
source.setAge(30);
source.setAddress("123 Main St");
SourceTargetMapper mapper = SourceTargetMapper.INSTANCE;
Target target = mapper.sourceToTarget(source);
System.out.println("Target Full Name: " + target.getFullName());
System.out.println("Target Age: " + target.getAge());
System.out.println("Target Location: " + target.getLocation());
}
}
與Spring集成
通過設置 componentModel = "spring",你可以將生成的 Mapper 實現類作為 Spring 組件進行管理,從而在 Spring 容器中進行依賴注入。
@Mapper(componentModel = "spring")
public interface SourceTargetMapper {
// 映射方法
}
使用如下
@Service
public class SomeService {
private final SourceTargetMapper sourceTargetMapper;
@Autowired
public SomeService(SourceTargetMapper sourceTargetMapper) {
this.sourceTargetMapper = sourceTargetMapper;
}
// 使用 sourceTargetMapper 進行對象轉換
}
表達式功能
可以使用 expression 屬性在 @Mapping 注解中指定自定義的表達式。
示例場景:假設我們有一個場景,需要將一個包含日期字符串的源對象轉換為目標對象,并且需要將日期字符串解析為 java.util.Date 對象。我們將使用 java.text.SimpleDateFormat 類來解析日期字符串。
public class Source {
private String dateString;
// getters and setters
}
public class Target {
private Date date;
// getters and setters
}
定義日期解析工具類
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateParser {
private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
public static Date parse(String dateString) throws ParseException {
return DATE_FORMAT.parse(dateString);
}
}
定義Mapper接口,注意注解中的imports和expression
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Mappings;
import org.mapstruct.factory.Mappers;
@Mapper(componentModel = "spring", imports = {DateParser.class, ParseException.class})
public interface SourceTargetMapper {
SourceTargetMapper INSTANCE = Mappers.getMapper(SourceTargetMapper.class);
@Mappings({
@Mapping(target = "date", expression = "java(DateParser.parse(source.getDateString()))")
})
Target sourceToTarget(Source source) throws ParseException;
}
在這個 Mapper接口中,使用了 imports 屬性導入了 DateParser 和 ParseException 類。然后在 @Mapping 注解的 expression 屬性中,通過 DateParser.parse(source.getDateString()) 來將 dateString 轉換為 Date 對象。
public class Main {
public static void main(String[] args) {
Source source = new Source();
source.setDateString("2024-11-25");
SourceTargetMapper mapper = SourceTargetMapper.INSTANCE;
try {
Target target = mapper.sourceToTarget(source);
System.out.println("Target Date: " + target.getDate());
} catch (ParseException e) {
e.printStackTrace();
}
}
}
在這個示例中,創(chuàng)建了一個包含日期字符串的 Source 對象,并使用 SourceTargetMapper 將其轉換為 Target 對象。轉換過程中,DateParser 類的 parse 方法被調用,將日期字符串解析為 Date 對象。
依賴:
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>1.5.5.Final</version> <!-- 請根據需要替換為最新版本 -->
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>1.5.5.Final</version> <!-- 請根據需要替換為最新版本 -->
<scope>provided</scope>
</dependency>
以上就是SpringBoot使用MapStruct生成映射代碼的示例詳解的詳細內容,更多關于SpringBoot MapStruct生成映射的資料請關注腳本之家其它相關文章!
相關文章
Spring Boot的filter(過濾器)簡單使用實例詳解
過濾器(Filter)的注冊方法和 Servlet 一樣,有兩種方式:代碼注冊或者注解注冊,下面通過實例給大家介紹Spring Boot的filter(過濾器)簡單使用,一起看看吧2017-04-04
Java詳細分析講解自動裝箱自動拆箱與Integer緩存的使用
裝箱就是把基本類型轉換成包裝類,拆箱就是把包裝類轉換成基本類型,下面這篇文章主要給大家介紹Java中自動裝箱、自動拆箱與Integer緩存,需要的朋友可以參考下2022-04-04
springboot集成mybaits-generator自動生成代碼的流程分析
這篇文章主要介紹了springboot集成mybaits-generator自動生成代碼的流程分析,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,感興趣的朋友一起看看吧2025-04-04

