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

Kri*_*hna 7 spring dependency-injection spring-boot 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);
}
Run Code Online (Sandbox Code Playgroud)

TypeMapper的代码如下,

@Component
@Mapper
public abstract class TypeMapper {

  public abstract Type mapType(DtoType DtoType);

  @InheritConfiguration(name = "mapType")
  public abstract DtoType mapDtoType(Type type);
}
Run Code Online (Sandbox Code Playgroud)

生成的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;
}

Run Code Online (Sandbox Code Playgroud)

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

Fil*_*lip 7

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

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

  • @Filip 我和 Robert 有同样的问题,使用 Spring Boot,但也想在普通的旧 JUnit 测试中使用我的映射器,而不是为此启动整个 Spring 上下文。它工作正常,但我宁愿避免警告...... (3认同)
  • 如果是这样的话,那么我就不会混合和匹配映射器。特别是如果您希望映射器之间存在依赖关系。也许您应该只使用默认的组件模型并在任何地方使用它。 (2认同)