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

MapStruct中MapperThree调用MapperTwo时MapperOne为空致空指针异常

问题原因

你通过org.mapstruct.factory.Mappers.getMapper()获取MapperTwo实例时,这个MapStruct原生工厂类不会处理Spring的依赖注入逻辑。MapperTwo依赖MapperOne,Spring版本的MapperTwo实现类中mapperOne是通过Spring注入的,但原生工厂创建的实例不会自动注入该依赖,导致mapperOne为null,触发空指针异常。

解决方案

方案一:通过Spring依赖注入使用MapperTwo(推荐)

利用Spring的依赖注入机制,让MapperThree直接依赖MapperTwo,MapStruct会自动为Spring组件生成处理依赖注入的实现类:

@Mapper(componentModel = "spring")
public interface MapperThree {
    // 声明依赖的MapperTwo,MapStruct会自动注入实例
    MapperTwo mapperTwo();

    default UserDTO convert(@NonNull final LoginWrapper loginWrapper) {
        final Login login = loginWrapper.getInstance();
        return mapperTwo().convert(login);
    }
}

方案二:手动注入依赖(不推荐)

如果必须使用Mappers.getMapper(),可以手动为MapperTwo实例设置MapperOne依赖,但这种方式脱离Spring容器管理,不符合规范:

@Mapper(componentModel = "spring")
public interface MapperThree {
    default UserDTO convert(@NonNull final LoginWrapper loginWrapper) {
        final Login login = loginWrapper.getInstance();
        MapperTwo mapperTwo = Mappers.getMapper(MapperTwo.class);
        // 手动注入MapperOne实例
        mapperTwo.setMapperOne(Mappers.getMapper(MapperOne.class));
        return mapperTwo.convert(login);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 01:52:43