栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot+Mybatis中Service单元测试时报错 Unsatisfied dependency expressed through field ‘XXXService‘;

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot+Mybatis中Service单元测试时报错 Unsatisfied dependency expressed through field ‘XXXService‘;

项目场景:

在编写SpringBoot+Mybatis项目时,进行Service单元测试时的报错


问题描述

主要问题:Unsatisfied dependency expressed through field ‘XXXService’;

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.passwordtranslate.Service.ServiceImpl.UsersServiceImplTest': Unsatisfied dependency expressed through field 'usersService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.passwordtranslate.Service.UsersService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: 
.......

原因分析:

ServiceBean没有成功注入Spring容器中


当前的结构目录:


Service层与Mapper均添加注释:


单元测试显示找不到该bean:


测试结果:


解决方案:

springboot启动类的默认扫描路径是该类所在的包下面的所有java类。如:启动类在“com.passwordtranslate.testone”包下,那么只有com.passwordtranslate.testone包下的类会被扫描加载。


将启动类移动至com.passwordtranslate包下(往上抬一阶)


启动类
(如果本文中提到的方法不奏效,也注意一下启动类的@MapperScan有没有添加和添加对(路径要到Mapper层所在的包))


Mapper类和Service类中的小bean图标出现


测试类中的bean也显示注入成功
(自己写的测试类@SpringBootTest一定要写上classes属性)


最后运行结果:成功查询

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/956659.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号