我正在使用 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/