框架推荐使用 ModelMapper 进行 Bean 复制,自动配置 ModelMapper 实例。

仓库坐标

Maven

<dependency>
    <groupId>com.luamas.thinkbridge</groupId>
    <artifactId>modelmapper-spring-boot-starter</artifactId>
</dependency>

Gradle

implementation("com.luamas.thinkbridge:modelmapper-spring-boot-starter")

基本使用

@Service
public class TestService {
    @Resource
    private TestMapper testMapper;
    @Resource
    private ModelMapper modelMapper;

    public int insert(TestDto testDto) {
        TestPojo testPojo = modelMapper.map(testDto, TestPojo.class);
        return testMapper.insert(testPojo);
    }
}

列表映射

List<TestPojo> pojos = testDtos.stream()
    .map(dto -> modelMapper.map(dto, TestPojo.class))
    .collect(Collectors.toList());

自定义映射规则

注册 ModelMapper 时添加自定义配置:

@Configuration
public class ModelMapperConfig {

    @Bean
    public ModelMapper modelMapper() {
        ModelMapper mapper = new ModelMapper();
        // 自定义属性映射
        mapper.typeMap(SourceDto.class, TargetDto.class)
            .addMapping(SourceDto::getFieldA, TargetDto::setFieldB);
        // 跳过null值
        mapper.getConfiguration()
            .setSkipNullEnabled(true);
        return mapper;
    }
}
ModelMapper 默认采用宽松匹配策略(LOOSE),如果需要严格匹配,可设置 mapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT)。