java - 使用java Mapstruct的模糊映射方法

标签 java mapstruct

我正在使用 java Mapstruct 将实体映射到 DTO

我想使用来自其他映射器的一个映射器,并且都使用相同的签名实现相同的方法,因此我得到“为映射属性找到的模糊映射方法”

我已经尝试在接口(interface)上实现共享方法,然后在两个映射器上扩展接口(interface),但问题仍然存在

我猜我需要使用某种限定符。我在谷歌和官方文档中进行了搜索,但我无法弄清楚如何应用此技术

// CHILD MAPPER ***
@Mapper(componentModel = "spring", uses = { })
public interface CustomerTagApiMapper {

CustomerTagAPI toCustomerTagApi(CustomerTag customerTag);

default OffsetDateTime fromInstant(Instant instant) {
    return instant == null ? null : instant.atOffset(ZoneOffset.UTC);
}
} 

// PARENT MAPPER ***
@Mapper(componentModel = "spring", uses = {  CustomerTagApiMapper.class })
public interface CustomerApiMapper {

CustomerAPI toCustomerApi(Customer customer);

default OffsetDateTime frmInstant(Instant instant) {
    return instant == null ? null : instant.atOffset(ZoneOffset.UTC);
}
}

最佳答案

使用限定符是解决此问题的一种方法。但是,在您的情况下,问题是 fromInstant 方法,它实际上是一个 util 方法。

为什么不将该方法提取到某个静态 util 类并告诉两个映射器也使用该类?

public class MapperUtils {

    public static OffsetDateTime fromInstant(Instant instant) {
        return instant == null ? null : instant.atOffset(ZoneOffset.UTC);
    }
}

然后你的映射器可以看起来像:

@Mapper(componentModel = "spring", uses = { MapperUtils.class })
public interface CustomerTagApiMapper {

    CustomerTagAPI toCustomerTagApi(CustomerTag customerTag);

}

@Mapper(componentModel = "spring", uses = {  CustomerTagApiMapper.class, MapperUtils.class })
public interface CustomerApiMapper {

    CustomerAPI toCustomerApi(Customer customer);

}

关于java - 使用java Mapstruct的模糊映射方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54609273/

相关文章:

java - Mapstruct - 在响应中发送具有(一对多关系)的嵌套实体

无法解析 Java 9 自动模块依赖项/找不到模块

java - 如何检查网站链接是否有数据(图片)或网站无效?

java - 小数位数和固定列格式

java - MapStruct 与 Spring Boot,使用自定义注释来注释生成的类

java - 如何在 Java 中将双向实体映射到 DTO

java - 应用程序在外部 Tomcat 上启动之前进行 Spring Boot 日志记录

java - Java for distcp中的Map Reduce作业

java - Mapstruct - 忽略集合内的属性

java - LocalDate 的 Mapstruct 默认值