Spring Boot集成MapStruct时CategoryMapper Bean找不到启动错误
问题分析与解决方案
核心问题
Spring容器无法找到CategoryMapper类型的Bean,本质是MapStruct的Mapper实现类未被正确生成,导致Spring无法扫描到对应的Bean实例。
修复步骤
1. 调整MapStruct版本与依赖
Spring Boot 3 + Java 17环境下,MapStruct 1.4.2.Final版本兼容性不足,先升级版本并补充编译期处理器依赖:
- 在
pom.xml的<properties>中更新版本:
<properties> <java.version>17</java.version> <org.mapstruct.version>1.5.5.Final</org.mapstruct.version> </properties>
- 在
<dependencies>中添加处理器依赖:
<dependency> <groupId>org.mapstruct</groupId> <artifactId>mapstruct-processor</artifactId> <version>${org.mapstruct.version}</version> <scope>provided</scope> </dependency>
2. 配置Maven编译插件
必须指定MapStruct处理器,确保编译时自动生成Mapper实现类,在<build>的<plugins>中添加:
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.10.1</version> <configuration> <source>${java.version}</source> <target>${java.version}</target> <annotationProcessorPaths> <path> <groupId>org.mapstruct</groupId> <artifactId>mapstruct-processor</artifactId> <version>${org.mapstruct.version}</version> </path> </annotationProcessorPaths> </configuration> </plugin>
3. 优化Mapper接口注解
@Mapper(componentModel = "spring")已自动标记生成的类为Spring Bean,无需额外添加@Component,修改后的Mapper接口:
package com.api.business_products_management.mappers; import com.api.business_products_management.dtos.CategoryDto; import com.api.business_products_management.models.CategoryModel; import org.mapstruct.Mapper; @Mapper(componentModel = "spring") public interface CategoryMapper { CategoryModel toCategoryModel(CategoryDto dto); }
4. 重新编译项目
执行命令清理旧编译文件并重新构建:
mvn clean compile
之后重启Spring Boot应用即可。
内容的提问来源于stack exchange,提问作者Routfin
相关产品推荐
相关产品推荐

