ModelMapper在SpringBoot中使用自定义配置

场景

有时候DTO与Model之间不一定是完全匹配上的,这个时候ModelMapper就不知道怎么处理,就需要我们手动处理两层之间的字段映射了。

解决

pom.xml

	<properties>
		<modelmapper.version>3.1.0modelmapper.version>
	properties>
...
		<dependencies>
			<dependency>
				<groupId>org.modelmapper.extensionsgroupId>
				<artifactId>modelmapper-springartifactId>
				<version>${modelmapper.version}version>
			dependency>
		dependencies>

ModelMapperConfig.java

@Configuration
public class ModelMapperConfig {
    @Bean
    public ModelMapper modelMapper() {
        ModelMapper modelMapper = new ModelMapper();
        modelMapper.typeMap(Order.class, OrderDTO.class).addMappings(mapper -> {
            mapper.map(src -> src.getBillingAddress().getStreet(),
                    Destination::setBillingStreet);
            mapper.map(src -> src.getBillingAddress().getCity(),
                    Destination::setBillingCity);
        });
        return modelMapper;
    }
}

参考:

  • ModelMapper in Spring Boot No Starter

你可能感兴趣的:(spring,modelmapper)