Java編碼輔助工具M(jìn)apstruct用法詳解
前言
項目開發(fā)中,業(yè)務(wù)分層會涉及不同類型的Bean之間需要相互轉(zhuǎn)換,如PO與DTO之間,PO與VO之間等。手動編碼setter/getter各個對應(yīng)屬性,會顯得臃腫繁瑣。通過Mapstruct框架可簡單方便地完成這一工作。
如何引入:
IntelliJ IDEA中安裝MapStruct Support插件:File -> Settings -> Plugins 搜索 MapStruct support 安裝,同時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")
定義對應(yīng)的Bean轉(zhuǎn)換方法:
public abstract XXXVO map(XXXPO xxxPo); public abstract List<XXXVO> map(List<XXXPO> xxxPos);
如果對應(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é)果對象
@BeforeMapping
在map屬性之前執(zhí)行某些操作
public void beforeListMap(Object anySource, @MappingTarget List<XXXPO> xxxVOs)
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Android中PreferenceFragment的使用詳解
本文主要介紹了Android中PreferenceFragment的使用詳解,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-09-09SpringBoot使用PropertiesLauncher加載外部jar包
這篇文章主要介紹了SpringBoot使用PropertiesLauncher加載外部jar包,本文結(jié)合實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-07-07SpringBoot+MyBatisPlus+Vue 前后端分離項目快速搭建過程(前端篇)
這篇文章主要介紹了SpringBoot+MyBatisPlus+Vue 前后端分離項目快速搭建過程(前端篇),本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-05-05Java求s=a+aa+aaa+aaaa+aa...a 5個數(shù)相加的值
求s=a+aa+aaa+aaaa+aa...a的值,其中a是一個數(shù)字。例如2+22+222+2222+22222(此時共有5個數(shù)相加),幾個數(shù)相加有鍵盤控制2017-02-02