首页 > 解决方案 > 使用componentModel =“spring”的Mapstruct依赖注入给出空对象

问题描述

我正在尝试使用 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为空。谁能阐明我在这里做错了什么?

标签: springspring-bootdependency-injectionmapstruct

解决方案


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

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


推荐阅读