You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Mapstruct:如何自动注入抽象类映射器?注入失败求助

问题分析与解决方案

核心原因

MapStruct的uses属性仅当当前Mapper实际调用了被引入Mapper的方法时,才会在生成的实现类中自动注入该Mapper实例。如果TestMapper中没有引用CommonLocationMapper的toLocationListCommon方法,生成的V1Impl就不会自动注入CommonLocationMapper。

具体修正步骤

  1. 在TestMapper中明确引用CommonLocationMapper的命名方法
    在TestMapper的映射方法里,通过@Mapping的qualifiedByName属性指定使用toLocationListCommon方法,示例:

    @Mapper(implementationName = "V1Impl", config = CommonMapper.CommonMapperConfig.class, uses = CommonLocationMapper.class)
    interface TestMapper {
        // 示例:在映射方法中关联CommonLocationMapper的命名方法
        @Mapping(source = "locList", target = "locations", qualifiedByName = "toLocationListCommon")
        TestDTO toTestDTO(TestEntity entity);
    
        // other mapping methods
    }
    
  2. 调整CommonLocationMapper方法的访问权限
    将toLocationListCommon方法改为public权限,避免跨包访问限制:

    @Mapper(componentModel = "spring")
    public abstract class CommonLocationMapper {
        @Setter(onMethod_ = @Autowired)
        protected TestService testService;
    
        @Named("toLocationListCommon")
        public List<Location> toLocationListCommon(List<? extends ILocation> loc) {
            //do mapping logic
        }
    }
    
  3. 验证Spring组件扫描范围
    确保CommonLocationMapper所在的包被Spring的@ComponentScan或@SpringBootApplication扫描覆盖,MapStruct生成的实现类会自动带有@Component注解,需要被Spring识别并注册为Bean。

  4. 检查MapStruct版本兼容性
    使用1.4.0及以上版本的MapStruct,确保与当前Spring版本兼容,避免因版本差异导致的注入异常。

内容的提问来源于stack exchange,提问作者ovod

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 08:10:29