项目开发中,业务分层会涉及不同类型的Bean之间需要相互转换,如PO与DTO之间,PO与VO之间等。手动编码setter/getter各个对应属性,会显得臃肿繁琐。通过Mapstruct框架可简单方便地完成这一工作。
如何引入:
IntelliJ IDEA中安装MapStruct Support插件:File -> Settings -> Plugins 搜索 MapStruct support 安装,同时File -> Settings -> Compiler -> Annotation Processors 勾选“Enable annotation processing”
pom.xml中加入依赖
org.mapstruct
mapstruct-jdk8
1.2.0.Final
provided
build配置
<build> <finalName>${project.artifactId}finalName> <plugins> <plugin> <groupId>org.apache.maven.pluginsgroupId> <artifactId>maven-compiler-pluginartifactId> <version>3.7.0version> <configuration> <annotationProcessorPaths> <path> <groupId>org.projectlombokgroupId> <artifactId>lombokartifactId> <version>1.16.18version> path> <path> <groupId>org.mapstructgroupId> <artifactId>mapstruct-processorartifactId> <version>1.2.0.Finalversion> path> annotationProcessorPaths> configuration> plugin> <plugin> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-maven-pluginartifactId> <version>${spring-boot.version}version> <executions> <execution> <goals> <goal>repackagegoal> goals> execution> executions> plugin> plugins> build>
常用注解使用
@Mapper, 修饰接口或抽象类, 如果使用spring来管理,则:@Mapper(componentModel = "spring")
定义对应的Bean转换方法:
public abstract XXXVO map(XXXPO xxxPo);
public abstract Listmap(List xxxPos);
如果对应属性名称不一致,则可通过
@Mappings(value={
@Mapping(target="abc", source="cba"),
@Mapping(target="acc", source="cca", qualifiedByName="mapMethodName2"), //定义转换的方法
@Mapping(target="aaa", constant="123") //定义常量
})
@AfterMapping // 在map属性完之后执行某些操作
public void afterListMap(@MappingTarget List
@BeforeMapping //在map属性之前执行某些操作
public void beforeListMap(Object anySource, @MappingTarget List