Java編碼輔助工具M(jìn)apstruct用法詳解
前言
項(xiàng)目開發(fā)中,業(yè)務(wù)分層會(huì)涉及不同類型的Bean之間需要相互轉(zhuǎn)換,如PO與DTO之間,PO與VO之間等。手動(dòng)編碼setter/getter各個(gè)對(duì)應(yīng)屬性,會(huì)顯得臃腫繁瑣。通過Mapstruct框架可簡(jiǎn)單方便地完成這一工作。
如何引入:
IntelliJ IDEA中安裝MapStruct Support插件:File -> Settings -> Plugins 搜索 MapStruct support 安裝,同時(shí)File -> Settings -> Compiler -> Annotation Processors 勾選“Enable annotation processing”
pom.xml中加入依賴
<dependency> <groupId>org.mapstruct</groupId> <artifactId>mapstruct-jdk8</artifactId> <version>1.2.0.Final</version> <scope>provided</scope> </dependency>
build配置
<build> <finalName>${project.artifactId}</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.7.0</version> <configuration> <annotationProcessorPaths> <path> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.18</version> </path> <path> <groupId>org.mapstruct</groupId> <artifactId>mapstruct-processor</artifactId> <version>1.2.0.Final</version> </path> </annotationProcessorPaths> </configuration> </plugin> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <version>${spring-boot.version}</version> <executions> <execution> <goals> <goal>repackage</goal> </goals> </execution> </executions> </plugin> </plugins> </build>
常用注解使用
@Mapper
修飾接口或抽象類, 如果使用spring來管理,則:@Mapper(componentModel = "spring")
定義對(duì)應(yīng)的Bean轉(zhuǎn)換方法:
public abstract XXXVO map(XXXPO xxxPo); public abstract List<XXXVO> map(List<XXXPO> xxxPos);
如果對(duì)應(yīng)屬性名稱不一致,則可通過
@Mappings(value={ @Mapping(target="abc", source="cba"), @Mapping(target="acc", source="cca", qualifiedByName="mapMethodName2"), //定義轉(zhuǎn)換的方法 @Mapping(target="aaa", constant="123") //定義常量 })
@AfterMapping
在map屬性完之后執(zhí)行某些操作
public void afterListMap(@MappingTarget List<XXXVO> xxxVOs) //map完的結(jié)果對(duì)象
@BeforeMapping
在map屬性之前執(zhí)行某些操作
public void beforeListMap(Object anySource, @MappingTarget List<XXXPO> xxxVOs)
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Android中PreferenceFragment的使用詳解
本文主要介紹了Android中PreferenceFragment的使用詳解,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-09-09SpringBoot使用PropertiesLauncher加載外部jar包
這篇文章主要介紹了SpringBoot使用PropertiesLauncher加載外部jar包,本文結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-07-07Java并發(fā)編程之Semaphore的使用簡(jiǎn)介
這篇文章主要介紹了Java并發(fā)編程之Semaphore的使用簡(jiǎn)介,幫助大家更好的理解和學(xué)習(xí)使用Java,感興趣的朋友可以了解下2021-04-04SpringBoot+MyBatisPlus+Vue 前后端分離項(xiàng)目快速搭建過程(前端篇)
這篇文章主要介紹了SpringBoot+MyBatisPlus+Vue 前后端分離項(xiàng)目快速搭建過程(前端篇),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-05-05Java求s=a+aa+aaa+aaaa+aa...a 5個(gè)數(shù)相加的值
求s=a+aa+aaa+aaaa+aa...a的值,其中a是一個(gè)數(shù)字。例如2+22+222+2222+22222(此時(shí)共有5個(gè)數(shù)相加),幾個(gè)數(shù)相加有鍵盤控制2017-02-02