欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringBoot使用MapStruct生成映射代碼的示例詳解

 更新時間:2024年11月26日 11:06:01   作者:鵬阿鵬  
MapStruct 是一個用于 Java 的代碼生成器,專門用于生成類型安全的 bean 映射代碼,它通過注解處理器在編譯時生成映射代碼,從而避免了運行時的性能開銷和潛在的錯誤,本文給大家介紹了SpringBoot使用MapStruct生成映射代碼的示例,需要的朋友可以參考下

定義

MapStruct 是一個用于 Java 的代碼生成器,專門用于生成類型安全的 bean 映射代碼。它通過注解處理器在編譯時生成映射代碼,從而避免了運行時的性能開銷和潛在的錯誤。

MapStruct 的主要目標是簡化和加速 Java 對象之間的轉換,特別是當這些對象具有相似的結構時。

相關概念

  • Mapper 接口 Mapper 接口定義了對象之間的映射方法。你可以通過在接口上使用 @Mapper
    注解來標記這個接口是一個映射器。MapStruct 會在編譯時生成這個接口的實現類。
  • Mapping 注解 @Mapping 注解用于定義源對象和目標對象之間的字段映射關系。你可以在 Mapper
    接口的方法上使用這個注解來指定具體的映射規(guī)則。
  • Mappings 注解 @Mappings 注解是 @Mapping 注解的容器,用于定義多個字段映射。
  • Component Model 通過 componentModel 屬性,你可以指定生成的 Mapper 實現類的組件模型,例如Spring、CDI 或默認的無組件模型。

使用示例

  1. 定義源對象和目標對象
public class Source {
    private String name;
    private int age;
    private String address;

    // getters and setters
}

public class Target {
    private String fullName;
    private int age;
    private String location;

    // getters and setters
}
  • 定義Mapper接口
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.factory.Mappers;

@Mapper
public interface SourceTargetMapper {

    SourceTargetMapper INSTANCE = Mappers.getMapper(SourceTargetMapper.class);

    @Mapping(source = "name", target = "fullName")
    @Mapping(source = "address", target = "location")
    Target sourceToTarget(Source source);

    @Mapping(source = "fullName", target = "name")
    @Mapping(source = "location", target = "address")
    Source targetToSource(Target target);
}

或者,可以使用 @Mappings 注解來包含多個 @Mapping 注解。@Mappings 注解是 @Mapping 注解的容器,用于定義多個字段映射。

import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Mappings;
import org.mapstruct.factory.Mappers;

@Mapper
public interface SourceTargetMapper {

    SourceTargetMapper INSTANCE = Mappers.getMapper(SourceTargetMapper.class);

    @Mappings({
        @Mapping(source = "name", target = "fullName"),
        @Mapping(source = "address", target = "location")
    })
    Target sourceToTarget(Source source);

    @Mappings({
        @Mapping(source = "fullName", target = "name"),
        @Mapping(source = "location", target = "address")
    })
    Source targetToSource(Target target);
}

  • 主方法
public class Main {
    public static void main(String[] args) {
        Source source = new Source();
        source.setName("John Doe");
        source.setAge(30);
        source.setAddress("123 Main St");

        SourceTargetMapper mapper = SourceTargetMapper.INSTANCE;
        Target target = mapper.sourceToTarget(source);

        System.out.println("Target Full Name: " + target.getFullName());
        System.out.println("Target Age: " + target.getAge());
        System.out.println("Target Location: " + target.getLocation());
    }
}

與Spring集成

通過設置 componentModel = "spring",你可以將生成的 Mapper 實現類作為 Spring 組件進行管理,從而在 Spring 容器中進行依賴注入。

@Mapper(componentModel = "spring")
public interface SourceTargetMapper {
    // 映射方法
}

使用如下

@Service
public class SomeService {

    private final SourceTargetMapper sourceTargetMapper;

    @Autowired
    public SomeService(SourceTargetMapper sourceTargetMapper) {
        this.sourceTargetMapper = sourceTargetMapper;
    }

    // 使用 sourceTargetMapper 進行對象轉換
}

表達式功能

可以使用 expression 屬性在 @Mapping 注解中指定自定義的表達式。

示例場景:假設我們有一個場景,需要將一個包含日期字符串的源對象轉換為目標對象,并且需要將日期字符串解析為 java.util.Date 對象。我們將使用 java.text.SimpleDateFormat 類來解析日期字符串。

public class Source {
    private String dateString;

    // getters and setters
}

public class Target {
    private Date date;

    // getters and setters
}

定義日期解析工具類

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateParser {
    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");

    public static Date parse(String dateString) throws ParseException {
        return DATE_FORMAT.parse(dateString);
    }
}

定義Mapper接口,注意注解中的imports和expression

import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Mappings;
import org.mapstruct.factory.Mappers;

@Mapper(componentModel = "spring", imports = {DateParser.class, ParseException.class})
public interface SourceTargetMapper {

    SourceTargetMapper INSTANCE = Mappers.getMapper(SourceTargetMapper.class);

    @Mappings({
        @Mapping(target = "date", expression = "java(DateParser.parse(source.getDateString()))")
    })
    Target sourceToTarget(Source source) throws ParseException;
}

在這個 Mapper接口中,使用了 imports 屬性導入了 DateParser 和 ParseException 類。然后在 @Mapping 注解的 expression 屬性中,通過 DateParser.parse(source.getDateString()) 來將 dateString 轉換為 Date 對象。

public class Main {
    public static void main(String[] args) {
        Source source = new Source();
        source.setDateString("2024-11-25");

        SourceTargetMapper mapper = SourceTargetMapper.INSTANCE;
        try {
            Target target = mapper.sourceToTarget(source);
            System.out.println("Target Date: " + target.getDate());
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}

在這個示例中,創(chuàng)建了一個包含日期字符串的 Source 對象,并使用 SourceTargetMapper 將其轉換為 Target 對象。轉換過程中,DateParser 類的 parse 方法被調用,將日期字符串解析為 Date 對象。

依賴:

<dependency>
    <groupId>org.mapstruct</groupId>
    <artifactId>mapstruct</artifactId>
    <version>1.5.5.Final</version> <!-- 請根據需要替換為最新版本 -->
</dependency>
<dependency>
    <groupId>org.mapstruct</groupId>
    <artifactId>mapstruct-processor</artifactId>
    <version>1.5.5.Final</version> <!-- 請根據需要替換為最新版本 -->
    <scope>provided</scope>
</dependency>

以上就是SpringBoot使用MapStruct生成映射代碼的示例詳解的詳細內容,更多關于SpringBoot MapStruct生成映射的資料請關注腳本之家其它相關文章!

相關文章

  • Java 格式化輸出JSON字符串的2種實現操作

    Java 格式化輸出JSON字符串的2種實現操作

    這篇文章主要介紹了Java 格式化輸出JSON字符串的2種實現操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-10-10
  • springboot自定義starter示例代碼

    springboot自定義starter示例代碼

    SpringBoot自定義Starter項目的命名建議遵循xxx-spring-boot-starter格式,以避免與官方或第三方Starter產生沖突,核心規(guī)范包括自動裝配文件的配置,旨在通過spring.factories或spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
    2024-11-11
  • Spring Boot的filter(過濾器)簡單使用實例詳解

    Spring Boot的filter(過濾器)簡單使用實例詳解

    過濾器(Filter)的注冊方法和 Servlet 一樣,有兩種方式:代碼注冊或者注解注冊,下面通過實例給大家介紹Spring Boot的filter(過濾器)簡單使用,一起看看吧
    2017-04-04
  • Java詳細分析講解自動裝箱自動拆箱與Integer緩存的使用

    Java詳細分析講解自動裝箱自動拆箱與Integer緩存的使用

    裝箱就是把基本類型轉換成包裝類,拆箱就是把包裝類轉換成基本類型,下面這篇文章主要給大家介紹Java中自動裝箱、自動拆箱與Integer緩存,需要的朋友可以參考下
    2022-04-04
  • Mybatis-Plus邏輯刪除的用法詳解

    Mybatis-Plus邏輯刪除的用法詳解

    這篇文章主要為大家詳細介紹了Mybatis-Plus 邏輯刪除的用法,文中有詳細的代碼示例,對我們的學習或工作有一定的幫助,需要的朋友可以參考下
    2023-07-07
  • java取某段/某個時間段的值的方法

    java取某段/某個時間段的值的方法

    這篇文章主要介紹了java取某段/某個時間段的值的方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-11-11
  • Java擴展庫RxJava的基本結構與適用場景小結

    Java擴展庫RxJava的基本結構與適用場景小結

    RxJava(GitHub: https://github.com/ReactiveX/RxJava)能夠幫助Java進行異步與事務驅動的程序編寫,這里我們來作一個Java擴展庫RxJava的基本結構與適用場景小結,剛接觸RxJava的同學不妨看一下^^
    2016-06-06
  • 淺談JAVA設計模式之享元模式

    淺談JAVA設計模式之享元模式

    這篇文章主要介紹了JAVA設計模式之享元模式的的相關資料,文中詳細的介紹了享元模式的概念以及使用方法,感興趣的朋友可以了解下
    2020-06-06
  • JavaWeb通過IDEA配置Servlet操作流程詳解

    JavaWeb通過IDEA配置Servlet操作流程詳解

    這篇文章主要介紹了JavaWeb通過IDEA配置Servlet實現流程,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習吧
    2022-10-10
  • springboot集成mybaits-generator自動生成代碼的流程分析

    springboot集成mybaits-generator自動生成代碼的流程分析

    這篇文章主要介紹了springboot集成mybaits-generator自動生成代碼的流程分析,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,感興趣的朋友一起看看吧
    2025-04-04

最新評論