本文主要是介绍springboot mapstruct,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
官网
官网
官方例子
POM
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.0.1.RELEASE</version>
<!-- -->
<!-- <version>2.5.15</version>--></parent><groupId>my.boot.test</groupId><artifactId>my-boot-test</artifactId><version>1.0-SNAPSHOT</version><packaging>jar</packaging><dependencies><!-- <dependency><groupId>org.junit.jupiter</groupId><artifactId>junit-jupiter-api</artifactId><scope>test</scope></dependency>--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><!--<version>1.16.20</version>--><version>1.18.16</version><scope>provided</scope></dependency><!-- swagger2 --><dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger2</artifactId><version>2.9.2</version></dependency><dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger-ui</artifactId><version>2.9.2</version></dependency><!-- mapstruct --><dependency><groupId>org.mapstruct</groupId><artifactId>mapstruct</artifactId><version>1.5.5.Final</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok-mapstruct-binding</artifactId><version>0.2.0</version></dependency><dependency><groupId>org.mapstruct</groupId><artifactId>mapstruct-processor</artifactId><version>1.5.5.Final</version><!--provided表明该包只在编译和测试的时候用--><scope>provided</scope></dependency><!-- spring-test --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>cn.hutool</groupId><artifactId>hutool-json</artifactId><version>5.8.25</version></dependency></dependencies><build><finalName>${project.artifactId}-8081</finalName><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><configuration><mainClass>com.boot.test.Application</mainClass></configuration></plugin></plugins></build></project>
DTO
AaDTO
import lombok.Data;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;@Data
public class AaDTO {private String str;private Integer intObjNum;private int intNum;private Date dateJUtil;private List<String> listStr;private Map<String,String> map;private BigDecimal bigDecimal;private String strA;private Integer intObjNumA;private int intNumA;private Date dateJUtilA;private List<String> listStrA;private Map<String,String> mapA;private BigDecimal bigDecimalA;
}
BbDTO
import lombok.Data;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;@Data
public class BbDTO {private String str;private Integer intObjNum;private int intNum;private Date dateJUtil;private List<String> listStr;private Map<String,String> map;private BigDecimal bigDecimal;
}
CcDTO
import lombok.Data;
import java.math.BigDecimal;@Data
public class CcDTO {private BigDecimal bigDecimal;private String nowDateStr;
}
DdDTO
import lombok.Data;@Data
public class DdDTO {private String s1;private String s2;private String s3;private String s4;
}
VO
import lombok.Data;import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;@Data
public class AaaVO {private String str;private Integer intObjNum;private int intNum;private Date dateJUtil;private String dateJUtilStr;private List<String> listStr;private Map<String,String> map;private BigDecimal bigDecimal;private String nowDateStr;private String intObjNumStr;
}
mapstruct 配置
import cn.hutool.core.util.IdUtil;
import com.boot.test.dto.AaDTO;
import com.boot.test.dto.CcDTO;
import com.boot.test.dto.DdDTO;
import com.boot.test.mapstruct.annotation.ToVO;
import com.boot.test.vo.AaaVO;
import org.mapstruct.*;import java.math.BigDecimal;
import java.util.List;
import java.util.Map;@Mapper(componentModel="spring",unmappedTargetPolicy = ReportingPolicy.IGNORE,imports = {cn.hutool.core.util.RandomUtil.class, IdUtil.class})
public interface MapStructConvertSpring {/*** Mapping注解的参数解释:* 1、source:源属性名称,即DTO类下的属性名称* 2、target:目标属性名称,即VO类下的属性名称* https://mapstruct.org/documentation/stable/reference/html/#datatype-conversions** before Java 8,需要用@Mappings包裹多个@Mapping*/@ToVO@Mapping(target = "intNum", ignore = true)@Mapping(target = "intObjNumStr",source = "intNum", numberFormat = "$#.00")@Mapping(target = "dateJUtilStr",source = "dateJUtil", dateFormat = "yyyy-MM-dd HH:mm:ss")AaaVO AaDTO2VO(AaDTO aaDTO);default AaaVO toDIY(AaDTO dto){AaaVO vo = new AaaVO();vo.setStr("toDIY + " +dto.getStr());return vo;}// 会把DTO里相同字段都转换到VO里@Mapping(target = "intObjNum", ignore = true)@Mapping(target = "str",source = "a.str")@Mapping(target = "bigDecimal",source = "c.bigDecimal")@Mapping(target = "intNum", source = "nn") //约定大于默认AaaVO AaBbDTO2VO(AaDTO a , CcDTO c,Integer nn);// 不成功@Mapping( target = ".", source = "str" )DdDTO default2VO(AaDTO dto);void updateVO( AaDTO dto,@MappingTarget AaaVO vo);@Mapping(target = "s1", source = "mk1")DdDTO mapToDTO(Map<String, String> map);@IterableMapping(numberFormat = "$#.00")List<String> prices(List<BigDecimal> prices);@InheritInverseConfigurationList<BigDecimal> pricesInverse(List<String> ll );@BeforeMappingdefault void before(){System.out.println("默认的前置转换...");}@BeforeMappingdefault void before(List<BigDecimal> prices,@MappingTarget List<String> ll){System.out.println("prices的前置转换...");}@AfterMappingdefault void after(){System.out.println("默认的后置转换...");}@AfterMappingdefault void after(List<BigDecimal> prices,@MappingTarget List<String> ll){System.out.println("prices的后置转换...");}@Mapping(target = "nowDateStr", source = "a.strA" ,defaultExpression = "java(IdUtil.fastSimpleUUID())")@Mapping(target = "intObjNum", source = "nn")@Mapping(target = "str",expression = "java(RandomUtil.randomString(a.getIntObjNum()) )")AaaVO randomAaDTO2VO(AaDTO a,Integer nn);}
springtest
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.boot.test.dto.AaDTO;
import com.boot.test.dto.BbDTO;
import com.boot.test.dto.CcDTO;
import com.boot.test.dto.DdDTO;
import com.boot.test.mapstruct.MapStructConvertSpring;
import com.boot.test.vo.AaaVO;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;import java.math.BigDecimal;
import java.util.*;@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
//SpringBoot2.2.0之前的版本 要加 @RunWith
@RunWith(SpringRunner.class)
public class AaaTestService {@Autowiredprivate MapStructConvertSpring convertSpring;AaDTO genAa(){AaDTO dto = new AaDTO();dto.setStr("strtttAAAAAAAA");dto.setIntObjNum(Integer.valueOf(111));dto.setIntNum(2222);dto.setDateJUtil(DateUtil.date());List<String> ll = new ArrayList<>();ll.add("a1");ll.add("a2");ll.add("a3");dto.setListStr(ll);Map<String,String> map =new HashMap<>();map.put("mk1","mv1");map.put("mk2","mv2");map.put("mk3","mv3");dto.setMap(map);dto.setBigDecimal(new BigDecimal("33.44"));return dto;}BbDTO genBb(){BbDTO dto = new BbDTO();dto.setStr("strtttBBBBBB");dto.setIntObjNum(Integer.valueOf(999));dto.setIntNum(888);dto.setListStr(Arrays.asList("b1","b2","b3"));dto.setBigDecimal(new BigDecimal("99.88"));return dto;}CcDTO genCc(){CcDTO dto = new CcDTO();dto.setBigDecimal(new BigDecimal("44.55"));dto.setNowDateStr("fsdgdfgdfgfd");return dto;}// 要经常clean@Testpublic void AaDtoV(){AaaVO vo = convertSpring.AaDTO2VO(genAa());System.out.println(JSONUtil.toJsonStr(vo));}@Testpublic void AaDtoVDIY(){AaaVO vo = convertSpring.toDIY(genAa());System.out.println(JSONUtil.toJsonStr(vo));}@Testpublic void AaBbDTO2VO(){AaaVO vo = convertSpring.AaBbDTO2VO(genAa(),genCc(),888888);System.out.println(JSONUtil.toJsonStr(vo));
// {"str":"strtttAAAAAAAA","intNum":2222,"dateJUtil":1706517743088,"listStr":["a1","a2","a3"],"map":{"mk1":"mv1","mk3":"mv3","mk2":"mv2"},"bigDecimal":44.55,"nowDateStr":"fsdgdfgdfgfd"}}@Testpublic void default2VO(){DdDTO ddDTO = convertSpring.default2VO(genAa());System.out.println(JSONUtil.toJsonStr(ddDTO));}@Testpublic void updateVO(){AaaVO vo = new AaaVO();convertSpring.updateVO(genAa(),vo);System.out.println(JSONUtil.toJsonStr(vo));}@Testpublic void mapToDTO(){Map<String,String> map =new HashMap<>();map.put("mk1","mv1");map.put("mk2","mv2");map.put("mk3","mv3");DdDTO dto = convertSpring.mapToDTO(map);System.out.println(JSONUtil.toJsonStr(dto));}@Testpublic void prices(){List<BigDecimal> ll= new ArrayList<>();ll.add(new BigDecimal("11.22"));ll.add(new BigDecimal("33.44"));ll.add(new BigDecimal("55.66"));ll.add(new BigDecimal("77.88"));List<String> prices = convertSpring.prices(ll);System.out.println(JSONUtil.toJsonStr(prices));}@Testpublic void pricesInverse(){List<BigDecimal> bigDecimals = convertSpring.pricesInverse(Arrays.asList("$3.44","$5.66","$7.88"));System.out.println(JSONUtil.toJsonStr(bigDecimals));}@Testpublic void randomAaDTO2VO(){AaaVO vo = convertSpring.randomAaDTO2VO(genAa(),8);System.out.println(JSONUtil.toJsonStr(vo));}
}
这篇关于springboot mapstruct的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!