当前位置: 代码网 > it编程>编程语言>Java > ModelMapper基本使用和常见场景示例详解

ModelMapper基本使用和常见场景示例详解

2025年06月26日 Java 我要评论
modelmapper 是一个用于简化 java 对象之间属性映射的库,它能够自动或通过自定义规则将一个对象的属性值映射到另一个对象中。以下是 modelmapper 的基本使用方法和常见场景示例:1

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 方法可以实现对象之间的属性映射。

示例:简单对象映射

假设有两个类 sourcedestination,它们的属性名相同:

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 的核心功能包括:

  1. 自动映射:根据属性名和类型自动映射。
  2. 自定义映射:通过 propertymap 或 lambda 表达式自定义映射规则。
  3. 集合映射:支持 listset 等集合类型的映射。
  4. 高级配置:支持匹配策略、忽略属性、自定义转换器等。
  5. spring 集成:可以轻松集成到 spring boot 项目中。

通过 modelmapper,可以大大减少对象映射的样板代码,提高开发效率。

到此这篇关于modelmapper基本使用和常见场景示例详解的文章就介绍到这了,更多相关modelmapper使用内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com