SpringBoot使用MapStruct生成映射代碼的示例詳解
定義
MapStruct 是一個(gè)用于 Java 的代碼生成器,專(zhuān)門(mén)用于生成類(lèi)型安全的 bean 映射代碼。它通過(guò)注解處理器在編譯時(shí)生成映射代碼,從而避免了運(yùn)行時(shí)的性能開(kāi)銷(xiāo)和潛在的錯(cuò)誤。
MapStruct 的主要目標(biāo)是簡(jiǎn)化和加速 Java 對(duì)象之間的轉(zhuǎn)換,特別是當(dāng)這些對(duì)象具有相似的結(jié)構(gòu)時(shí)。
相關(guān)概念
Mapper
接口 Mapper 接口定義了對(duì)象之間的映射方法。你可以通過(guò)在接口上使用 @Mapper
注解來(lái)標(biāo)記這個(gè)接口是一個(gè)映射器。MapStruct 會(huì)在編譯時(shí)生成這個(gè)接口的實(shí)現(xiàn)類(lèi)。Mapping
注解 @Mapping 注解用于定義源對(duì)象和目標(biāo)對(duì)象之間的字段映射關(guān)系。你可以在 Mapper
接口的方法上使用這個(gè)注解來(lái)指定具體的映射規(guī)則。Mappings
注解 @Mappings 注解是 @Mapping 注解的容器,用于定義多個(gè)字段映射。Component Model
通過(guò) componentModel 屬性,你可以指定生成的 Mapper 實(shí)現(xiàn)類(lèi)的組件模型,例如Spring、CDI 或默認(rèn)的無(wú)組件模型。
使用示例
- 定義源對(duì)象和目標(biāo)對(duì)象
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 注解來(lái)包含多個(gè) @Mapping 注解。@Mappings 注解是 @Mapping 注解的容器,用于定義多個(gè)字段映射。
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集成
通過(guò)設(shè)置 componentModel = "spring"
,你可以將生成的 Mapper 實(shí)現(xiàn)類(lèi)作為 Spring 組件進(jìn)行管理,從而在 Spring 容器中進(jìn)行依賴(lài)注入。
@Mapper(componentModel = "spring") public interface SourceTargetMapper { // 映射方法 }
使用如下
@Service public class SomeService { private final SourceTargetMapper sourceTargetMapper; @Autowired public SomeService(SourceTargetMapper sourceTargetMapper) { this.sourceTargetMapper = sourceTargetMapper; } // 使用 sourceTargetMapper 進(jìn)行對(duì)象轉(zhuǎn)換 }
表達(dá)式功能
可以使用 expression 屬性在 @Mapping 注解中指定自定義的表達(dá)式。
示例場(chǎng)景:假設(shè)我們有一個(gè)場(chǎng)景,需要將一個(gè)包含日期字符串的源對(duì)象轉(zhuǎn)換為目標(biāo)對(duì)象,并且需要將日期字符串解析為 java.util.Date 對(duì)象。我們將使用 java.text.SimpleDateFormat 類(lèi)來(lái)解析日期字符串。
public class Source { private String dateString; // getters and setters } public class Target { private Date date; // getters and setters }
定義日期解析工具類(lèi)
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; }
在這個(gè) Mapper接口中,使用了 imports 屬性導(dǎo)入了 DateParser 和 ParseException 類(lèi)。然后在 @Mapping 注解的 expression 屬性中,通過(guò) DateParser.parse(source.getDateString()) 來(lái)將 dateString 轉(zhuǎn)換為 Date 對(duì)象。
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(); } } }
在這個(gè)示例中,創(chuàng)建了一個(gè)包含日期字符串的 Source 對(duì)象,并使用 SourceTargetMapper 將其轉(zhuǎn)換為 Target 對(duì)象。轉(zhuǎn)換過(guò)程中,DateParser 類(lèi)的 parse 方法被調(diào)用,將日期字符串解析為 Date 對(duì)象。
依賴(lài):
<dependency> <groupId>org.mapstruct</groupId> <artifactId>mapstruct</artifactId> <version>1.5.5.Final</version> <!-- 請(qǐng)根據(jù)需要替換為最新版本 --> </dependency> <dependency> <groupId>org.mapstruct</groupId> <artifactId>mapstruct-processor</artifactId> <version>1.5.5.Final</version> <!-- 請(qǐng)根據(jù)需要替換為最新版本 --> <scope>provided</scope> </dependency>
以上就是SpringBoot使用MapStruct生成映射代碼的示例詳解的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot MapStruct生成映射的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Java 格式化輸出JSON字符串的2種實(shí)現(xiàn)操作
這篇文章主要介紹了Java 格式化輸出JSON字符串的2種實(shí)現(xiàn)操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-10-10Spring Boot的filter(過(guò)濾器)簡(jiǎn)單使用實(shí)例詳解
過(guò)濾器(Filter)的注冊(cè)方法和 Servlet 一樣,有兩種方式:代碼注冊(cè)或者注解注冊(cè),下面通過(guò)實(shí)例給大家介紹Spring Boot的filter(過(guò)濾器)簡(jiǎn)單使用,一起看看吧2017-04-04Java詳細(xì)分析講解自動(dòng)裝箱自動(dòng)拆箱與Integer緩存的使用
裝箱就是把基本類(lèi)型轉(zhuǎn)換成包裝類(lèi),拆箱就是把包裝類(lèi)轉(zhuǎn)換成基本類(lèi)型,下面這篇文章主要給大家介紹Java中自動(dòng)裝箱、自動(dòng)拆箱與Integer緩存,需要的朋友可以參考下2022-04-04Java擴(kuò)展庫(kù)RxJava的基本結(jié)構(gòu)與適用場(chǎng)景小結(jié)
RxJava(GitHub: https://github.com/ReactiveX/RxJava)能夠幫助Java進(jìn)行異步與事務(wù)驅(qū)動(dòng)的程序編寫(xiě),這里我們來(lái)作一個(gè)Java擴(kuò)展庫(kù)RxJava的基本結(jié)構(gòu)與適用場(chǎng)景小結(jié),剛接觸RxJava的同學(xué)不妨看一下^^2016-06-06JavaWeb通過(guò)IDEA配置Servlet操作流程詳解
這篇文章主要介紹了JavaWeb通過(guò)IDEA配置Servlet實(shí)現(xiàn)流程,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧2022-10-10springboot集成mybaits-generator自動(dòng)生成代碼的流程分析
這篇文章主要介紹了springboot集成mybaits-generator自動(dòng)生成代碼的流程分析,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,感興趣的朋友一起看看吧2025-04-04