modelMapper入门及使用解析

您所在的位置:网站首页 modelmapper modelMapper入门及使用解析

modelMapper入门及使用解析

2023-01-25 13:46| 来源: 网络整理| 查看: 265

在开发过程中经常会有一个需求,就是类型转换 (把一个类转成另一个类)modelmapper就是一个提高生产力的工具 入门 内置匹配器 自定义匹配器 源码映射解析 入门 方式1 (默认配置) 导入maven依赖 org.modelmapper modelmapper 2.3.0 新建三个实体 public class AppleVo { private String name ; private String id ; } public class Apple { private String id ; private String name ; private String createAge ; } public class AppleDTO { private String name ; private String create_age ; } 测试 public static Apple apple; public static List apples; /** * 模拟数据 */ static { apple = new Apple(); apple.setName("black"); apple.setCreateAge("22"); apple.setId("1"); apples = new ArrayList(16); Apple apple1 = new Apple("1", "red", "21"); Apple apple2 = new Apple("2", "blue", "22"); Apple apple3 = new Apple("3", "yellow", "23"); apples.add(apple1); apples.add(apple2); apples.add(apple3); } /** * * 属性名保持一致,采用默认规则 */ public void test1() { ModelMapper modelMapper = new ModelMapper(); AppleDTO appleDto = modelMapper.map(apple, AppleDTO.class); System.out.println(appleDto.toString()); }

使用内置匹配策略

官方提供了多种匹配策略,可以去官网详细了解

image.png public void test2() { ModelMapper modelMapper = new ModelMapper(); modelMapper.getConfiguration() /** LOOSE松散策略 */ .setMatchingStrategy(MatchingStrategies.LOOSE); AppleDTO appleDto = modelMapper.map(apple, AppleDTO.class); System.out.println(appleDto.toString()); } 自定义映射规则 private static PropertyMap customField(){ /** * 自定义映射规则 */ return new PropertyMap() { @Override protected void configure() { /**使用自定义转换规则*/ map(source.getCreateAge(),destination.getCreate_age()); } }; } public void test4(){ ModelMapper modelMapper = new ModelMapper(); modelMapper.addMappings(customField()) ; List userDTOS = modelMapper.map(apples,new TypeToken() {}.getType()); System.out.println(userDTOS); } 源码映射解析

在mappermodel中,一般情况下保持属性名一致即可以不用任何配置就可直接转换,mappermodel的原理是基于反射原理进行赋值的,或是直接对成员变量赋值的,走一波debug,如图

//入口方法 public D map(S source, Class sourceType, D destination, TypeToken destinationTypeToken, String typeMapName) {} //类型映射 D typeMap(MappingContextImpl context, TypeMap typeMap) { } image.png //属性赋值 private void setDestinationValue(MappingContextImpl context, MappingContextImpl propertyContext, MappingImpl mapping) {} image.png


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3