MapStruct @DecoratedWith注解无法注入delegate Bean求助
MapStruct @DecoratedWith 空指针异常排查与解决
问题根源
- 版本兼容性冲突:MapStruct 1.4.1.Final与Spring Boot 2.7.0依赖的Spring Context 5.3.x在Bean注册逻辑上存在适配问题,导致装饰器的delegate实例无法被Spring正确注入。
- 装饰器限定符配置错误:
DecClass中使用的@Qualifier("delegate")不符合MapStruct Spring组件模型的默认委托Bean命名规范。
修复步骤
1. 升级MapStruct版本
将MapStruct版本升级至1.5.3.Final(该版本完美适配Spring Boot 2.7.x系列),修改pom.xml依赖:
<dependency> <groupId>org.mapstruct</groupId> <artifactId>mapstruct</artifactId> <version>1.5.3.Final</version> </dependency> <dependency> <groupId>org.mapstruct</groupId> <artifactId>mapstruct-processor</artifactId> <version>1.5.3.Final</version> <scope>provided</scope> </dependency>
2. 修正装饰器的delegate注入
将DecClass中的限定符替换为MapStruct Spring组件模型的默认值:
@Autowired @Qualifier("mapstruct-delegate") private IMyMapper delegate;
3. 确认Mapper接口配置
保证IMyMapper的注解配置无误:
@Mapper(componentModel = "spring") @DecoratedWith(DecClass.class) public interface IMyMapper { Person1 toPerson1(Person2 person2); }
4. 重新构建项目
执行Maven命令清理并重新编译:
mvn clean install
验证
运行测试代码,此时IMyMapperImpl中的delegate会被Spring正确注入,空指针异常将不再出现。
内容的提问来源于stack exchange,提问作者DockYard
相关产品推荐
相关产品推荐

