使用 componentModel = "spring" 的 Mapstruct 依赖注入给出空对象

Mapstruct dependency injection using componentModel = "spring" gives null object

我正在尝试使用 Spring 注入映射器对象(class 是 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 为空。谁能阐明我在这里做错了什么?

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

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