我正在尝试使用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
为空。谁能说明我在这里做错了什么?
答案 0 :(得分:1)
TypeMapper
不使用弹簧componentModel
。您需要从@Component
中删除TypeMapper
,而使用@Mapper(componentModel = "spring")
。
如果您使用AttachmentMapper MAPPER = Mappers.getMapper(AttachmentMapper.class);
来获取映射器,那么这是错误的,因为Mappers
工厂只能与default
componentModel
一起使用。如果您使用的是Spring,则应该注入您的映射器。