如何配置ModelMapper实现严格类型映射校验?类型不匹配时触发失败
ModelMapper 严格类型映射配置问题
我发现两个类的同一属性类型存在细微差异:double与Double,导致null Double会自动转换为0.0 double。甚至当该属性在一侧被定义为String类型时,也不会触发任何校验错误。请问ModelMapper中是否存在相关配置,可要求属性间进行严格类型映射,即当类型不完全相同时触发校验失败?
示例代码:
public class MyCarDto { public double numberOfWheels; } public class MyCarDao { public Double numberOfWheels; } public class MyCarMapper { private final ModelMapper modelMapper; public MyCarMapper() { modelMapper = new ModelMapper(); modelMapper.typeMap(MyCarDto.class, MyCarDao.class); // should throw an exception saying property numberOfWheels should be exact same type modelMapper.validate(); } }
解决方案
ModelMapper 默认会自动处理基本类型与包装类型、跨类型(如String转数值)的隐式转换,不会主动触发类型不匹配的校验错误。要实现严格的类型匹配校验,可通过以下几种方式实现:
- 启用严格匹配策略
先配置MatchingStrategies.STRICT,让ModelMapper在属性匹配阶段优先要求类型完全一致,这是基础配置:
modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
- 为单个TypeMap添加类型校验
针对特定的类型映射,直接为属性添加类型匹配校验:
modelMapper.typeMap(MyCarDto.class, MyCarDao.class) .addMappings(mapper -> mapper.validateTypeMatch(MyCarDto::numberOfWheels, MyCarDao::numberOfWheels));
- 全局自定义严格类型校验器
如果需要对所有类型映射生效,可以实现Validator接口并注册到ModelMapper,在validate()时自动校验所有属性的类型一致性:
public class StrictTypeValidator implements Validator { @Override public void validate(TypeMap<?, ?> typeMap) { typeMap.getPropertyMappings().forEach(mapping -> { Class<?> sourceType = mapping.getSourceType(); Class<?> destType = mapping.getDestinationType(); if (!sourceType.equals(destType)) { throw new ValidationException(String.format( "属性'%s'类型不匹配:源类型%s,目标类型%s", mapping.getDestinationName(), sourceType.getName(), destType.getName() )); } }); } } // 注册校验器 modelMapper.getConfiguration().addValidator(new StrictTypeValidator());
完成上述配置后,调用modelMapper.validate()时,只要属性类型不完全一致,就会抛出ValidationException,满足严格类型映射的需求。
内容的提问来源于stack exchange,提问作者KrisG
相关产品推荐
相关产品推荐

