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为空。谁能阐明我在这里做错了什么?
不TypeMapper使用弹簧componentModel。您需要@Component从 中删除TypeMapper并使用@Mapper(componentModel = "spring")它。
如果您使用AttachmentMapper MAPPER = Mappers.getMapper(AttachmentMapper.class);来获取映射器,那么这是错误的,因为Mappers工厂只能与default componentModel. 如果您使用 Spring,则应该注入映射器。
| 归档时间: |
|
| 查看次数: |
15433 次 |
| 最近记录: |