【问题标题】:Mapstruct dependency injection using componentModel = "spring" gives null object使用componentModel =“spring”的Mapstruct依赖注入给出空对象
【发布时间】:2019-06-17 15:38:07
【问题描述】:

我正在尝试使用 Spring 注入映射器对象(类为 TypeMapper)依赖项,如下所示,

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

  AttachmentMapper MAPPER = Mappers.getMapper(AttachmentMapper.class);

  @Mappings({
      @Mapping(source = "type", target = "type") })
  AttachmentDTO toDTO(Attachment attachment);
}

TypeMapper的代码如下,

@Component
@Mapper
public abstract class TypeMapper {

  public abstract Type mapType(DtoType DtoType);

  @InheritConfiguration(name = "mapType")
  public abstract DtoType mapDtoType(Type type);
}

生成的AttachmentMapperImpl代码如下,

public class AttachmentMapperImpl implements AttachmentMapper {

    @Autowired

    private TypeMapper typeMapper;

    public AttachmentDto toDTO(Attachment attachment) {

    if ( attachment == null) {
        return null;
    }

    attachmentDTO.setType(typeMapper.mapDtoType(attachment.getType()));

    return attachmentDTO;
}

问题出在生成的代码中,@Autowired typeMapper 为空。谁能阐明我在这里做错了什么?

【问题讨论】:

    标签: spring spring-boot dependency-injection mapstruct


    【解决方案1】:

    TypeMapper 不使用弹簧componentModel。您需要从TypeMapper 中删除@Component 并改用@Mapper(componentModel = "spring")

    如果您使用AttachmentMapper MAPPER = Mappers.getMapper(AttachmentMapper.class); 来获取映射器,那么这是错误的,因为Mappers 工厂只能与default componentModel 一起使用。如果你使用的是 Spring,你应该注入你的映射器。

    【讨论】:

    • 谢谢菲利普。总的来说,我是 Mapstruct 和 spring 的新手,并且很难理解出了什么问题。我已经删除了@Mapper(componentModel = "spring") 并将其设为默认值并且它有效。感谢您的洞察力。
    • @Filip 你说:如果你使用的是 Spring,你应该注入你的映射器。我不能在上下文之外使用 spring 组件。这个怎么样:我在春天和春天以外需要相同的映射器。最佳做法是什么?
    • 你的意思是你不能在上下文之外使用 Spring?你在用还是不用Spring?
    • 我在我的项目中使用 Spring Boot,但我有一些类没有@Component@Bean 注释。我想在这些类中使用映射器。如果我将映射器与 componentModel = "spring" 一起使用,我可以将映射器注入这些类。
    • 如果是这样,那我就不会混合和匹配映射器。特别是如果您想在映射器之间建立依赖关系。也许您应该只使用默认组件模型并在任何地方使用它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-12
    • 2015-07-15
    • 1970-01-01
    • 2011-09-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多