spring - 使用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
为空。谁能阐明我在这里做错了什么?
解决方案
TypeMapper
不使用弹簧componentModel
。您需要@Component
从 the中删除TypeMapper
并@Mapper(componentModel = "spring")
改为使用。
如果您AttachmentMapper MAPPER = Mappers.getMapper(AttachmentMapper.class);
用于获取映射器,那么这是错误的,因为Mappers
工厂只能与default
componentModel
. 如果您使用的是 Spring,则应该注入映射器。
推荐阅读
- visual-studio - 为什么 Visual Studio 2019 会在构建后删除我引用的程序集?
- authentication - 具有非对称加密和简单 API 的 NFC 标签
- python - 打印网页后的无头 Chrome Webdriver 问题
- unreal-engine4 - 将动画引用传递给 animbp 蓝图
- python - 如何使用python按行名合并两个文件
- mongodb - 如何减少map reduce编程中的输出?
- javascript - 范围内的 Jquery 折扣计算
- mysql - 使用 Inner Join 消除有效冗余的条目
- android - 需要帮助在绝对没有内置程序的设备上安装应用程序来安装任何东西
- python - 在 initial_text 和 input_text django 表单后删除冒号