首页 > 解决方案 > MapStruct 使用 Spring Boot 接口导致 NoSuchBeanDefinitionException

问题描述

我已经实现了一个使用接口MapStruct

@Mapper(componentModel = "spring")
public interface MapStructMapper {

    MapStructMapper INSTANCE = Mappers.getMapper( MapStructMapper.class );

    MyApiModel myInternalClassToMyApiModel(MyDocument.MyInternalClass myInternalClass);
    MyDocument.MyInternalClass myApiModelToMyInternalClass(MyApiModel myApiModel);
}

运行 gradle build 时,执行测试时出现以下异常:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'MapStructMapper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

在我的测试课中,我目前只有:

@Autowired
protected MapStructMapper mapper;

在我的 build.gradle

implementation 'org.mapstruct:mapstruct:1.4.2.Final'
annotationProcessor 'org.mapstruct:mapstruct-processor:1.4.2.Final'

如果我通过接口使用 MapStruct,我该如何解决这个问题以及如何调用映射?

标签: spring-bootexceptioninterfacemapstruct

解决方案


根据您提供的信息,很难给出明确的答案。

请检查您是否不仅在构建中包含了 mapstruct 依赖项,还包含注释处理器,以便MapStructMapperImpl实际生成。

如果确实生成了它,则必须确保它包含在测试的应用程序上下文中。如果使用@SpringBootTest,则需要确保接口声明在组件扫描所扫描的包中。如果您使用 构造专用上下文@ContextConfiguration,则需要在列表MapStructMapperImpl.class中列出您传递给参数的列表,classes就像使用其他注释的类一样@Component


推荐阅读