admin管理员组文章数量:1530085
项目场景:
在编写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属性)
最后运行结果:成功查询
本文标签: 时报单元测试MyBatisServiceSpringBoot
版权声明:本文标题:SpringBoot+Mybatis中Service单元测试时报错 Unsatisfied dependency expressed through field ‘XXXService‘; 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://m.elefans.com/dianzi/1725805155a1043934.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论