Mapstruct调用Spring Bean Mapper未初始化致空指针异常求解
解决MapStruct跨Mapper调用时Spring依赖注入为空的问题
问题原因
你用Mappers.getMapper(ProductCountMapper.class)获取Mapper实例时,走的是MapStruct默认实例化逻辑——直接创建新对象,完全脱离Spring容器管理。因此ProductCountMapper中@Autowired的ProductService不会被Spring注入,触发NullPointerException。而单独使用ProductCountMapper时,实例由Spring容器创建,依赖注入正常生效。
解决方案
方案一:通过Spring注入ProductCountMapper替代手动获取
直接在WishListMapper中用@Autowired注入ProductCountMapper,借助Spring的依赖管理能力获取正确实例:
@Mapper(componentModel = MappingConstants.ComponentModel.SPRING) public abstract class WishListMapper { @Autowired protected ProductCountMapper productCountMapper; @Mappings ({ @Mapping(source = "productCountDtos", target = "productCounts", qualifiedByName = "productCountDtosToProductCounts"), @Mapping(target = "account", ignore = true), @Mapping(target = "id", ignore = true) }) public abstract WishList mapToWishList(WishListDto wishListDto); @Named("productCountDtosToProductCounts") Set<ProductCount> productCountDtosToProductCounts(List<ProductCountDto> productCountDtos) { return productCountDtos.stream() .map(productCountMapper::mapToProductCount) .collect(Collectors.toSet()); } }
方案二:使用MapStruct的uses属性关联Mapper(推荐)
利用MapStruct原生的uses属性,让框架自动处理Mapper间的依赖和转换逻辑,无需手动编写遍历转换代码:
@Mapper(componentModel = MappingConstants.ComponentModel.SPRING, uses = ProductCountMapper.class) public abstract class WishListMapper { @Mappings ({ @Mapping(source = "productCountDtos", target = "productCounts"), @Mapping(target = "account", ignore = true), @Mapping(target = "id", ignore = true) }) public abstract WishList mapToWishList(WishListDto wishListDto); }
MapStruct会自动识别ProductCountMapper中的mapToProductCount方法,完成List<ProductCountDto>到Set<ProductCount>的转换,同时Spring会自动注入ProductCountMapper的容器实例,保证依赖正常注入。
内容的提问来源于stack exchange,提问作者Emilien Brigand
相关产品推荐
相关产品推荐

