ModelMapper 是一个用于简化 Java 对象之间属性映射的库,它能够自动或通过自定义规则将一个对象的属性值映射到另一个对象中。以下是 ModelMapper 的基本使用方法和常见场景示例:
1. 添加依赖
首先,需要在项目中添加 ModelMapper 的依赖。如果你使用 Maven,可以在 pom.xml
中添加以下依赖:
<dependency>
<groupId>org.modelmapper</groupId>
<artifactId>modelmapper</artifactId>
<version>3.1.1</version> <!-- 使用最新版本 -->
</dependency>
2. 基本用法
ModelMapper 的核心是 ModelMapper
类,通过它的 map
方法可以实现对象之间的属性映射。
示例:简单对象映射
假设有两个类 Source
和 Destination
,它们的属性名相同:
import org.modelmapper.ModelMapper;
class Source {
private String name;
private int age;
// getters and setters
}
class Destination {
private String name;
private int age;
// getters and setters
}
public class Main {
public static void main(String[] args) {
ModelMapper modelMapper = new ModelMapper();
Source source = new Source();
source.setName("Alice");
source.setAge(25);
// 将 Source 对象映射到 Destination 对象
Destination destination = modelMapper.map(source, Destination.class);
System.out.println(destination.getName()); // 输出: Alice
System.out.println(destination.getAge()); // 输出: 25
}
}
3. 自定义映射规则
如果源对象和目标对象的属性名不同,或者需要更复杂的映射逻辑,可以通过以下方式自定义:
方式 1:使用 PropertyMap
import org.modelmapper.PropertyMap;
ModelMapper modelMapper = new ModelMapper();
// 自定义映射规则
modelMapper.addMappings(new PropertyMap<Source, Destination>() {
@Override
protected void configure() {
map().setUserName(source.getName()); // 将 Source 的 name 映射到 Destination 的 userName
map().setYears(source.getAge()); // 将 Source 的 age 映射到 Destination 的 years
}
});
Source source = new Source();
source.setName("Bob");
source.setAge(30);
Destination destination = modelMapper.map(source, Destination.class);
System.out.println(destination.getUserName()); // 输出: Bob
System.out.println(destination.getYears()); // 输出: 30
方式 2:使用 Lambda 表达式(ModelMapper 2.3.0+)
ModelMapper modelMapper = new ModelMapper();
// 使用 Lambda 表达式自定义映射
modelMapper.typeMap(Source.class, Destination.class)
.addMappings(mapper -> mapper.map(src -> src.getName(), Destination::setUserName))
.addMappings(mapper -> mapper.map(src -> src.getAge(), Destination::setYears));
Destination destination = modelMapper.map(source, Destination.class);
4. 集合映射
ModelMapper 也支持集合类型的映射,例如将 List<Source>
映射为 List<Destination>
:
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
List<Source> sources = Arrays.asList(
new Source("Alice", 25),
new Source("Bob", 30)
);
// 方法 1:使用 Stream 和 map
List<Destination> destinations = sources.stream()
.map(source -> modelMapper.map(source, Destination.class))
.collect(Collectors.toList());
// 方法 2:直接映射集合(ModelMapper 2.3.0+)
List<Destination> destinations2 = modelMapper.map(sources, new TypeToken<List<Destination>>() {}.getType());
5. 高级配置
匹配策略
ModelMapper 提供了多种匹配策略,例如:
STRICT
:严格匹配(默认),属性名和类型必须完全一致。LOOSE
:宽松匹配,属性名可以部分匹配。STANDARD
:标准匹配,支持驼峰命名转换。
modelMapper.getConfiguration()
.setMatchingStrategy(MatchingStrategies.LOOSE); // 使用宽松匹配
忽略某些属性
modelMapper.typeMap(Source.class, Destination.class)
.addMappings(mapper -> mapper.skip(Destination::setAge)); // 忽略 age 属性的映射
自定义转换器
如果需要将属性值进行转换(例如日期格式化),可以使用 Converter
:
import org.modelmapper.Converter;
import org.modelmapper.spi.MappingContext;
Converter<String, Date> stringToDateConverter = ctx -> {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
return sdf.parse(ctx.getSource());
} catch (ParseException e) {
throw new RuntimeException(e);
}
};
modelMapper.addConverter(stringToDateConverter);
6. 在 Spring Boot 中使用
在 Spring Boot 项目中,可以将 ModelMapper 配置为 Bean:
import org.modelmapper.ModelMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
@Bean
public ModelMapper modelMapper() {
return new ModelMapper();
}
}
然后在 Service 或 Controller 中注入使用:
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
private ModelMapper modelMapper;
public Destination convertToDestination(Source source) {
return modelMapper.map(source, Destination.class);
}
}
总结
ModelMapper 的核心功能包括:
- 自动映射:根据属性名和类型自动映射。
- 自定义映射:通过
PropertyMap
或 Lambda 表达式自定义映射规则。 - 集合映射:支持
List
、Set
等集合类型的映射。 - 高级配置:支持匹配策略、忽略属性、自定义转换器等。
- Spring 集成:可以轻松集成到 Spring Boot 项目中。
通过 ModelMapper,可以大大减少对象映射的样板代码,提高开发效率。