测试SpringBoot的时候报错mapper未装载的解决方案:

1.报错信息和截图:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.tang.testspringboot.TestSpringBootApplicationTests': Unsatisfied dependency expressed through field 'mapper': No qualifying bean of type 'com.tang.mapper.Mapper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

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

已经把springboot的所有的依赖准备好了,mapper也写好了,在测试的时候报上面的错。

2.分析过程:

2.1SpringBoot装载类的机制:

看报错的意思是这个mapper的类没有放到springboot的容器里面,从spring的学习中应该知道,在注解方式的spring开发中只有一种方式将类放到容器里面,这种在spring的容器的配置类中直接开启一个ComponentScan扫描的注解,它会去扫描我们标记了@controller @Reposity @Service注解的这些类,从而把类放到容器中,最开始是不用扫,是我们把类的名字写到我们的bean文件里面即可。正好springboot也是这种机制,SpringBoot启动类上面的@SpringBootApplication里面有一个@ComponentScan,它可以扫描启动类同级及其子级包下的所有文件,并且把带有@Component、@Repository、@Service、@Controller的类注册到Spring容器。

@Component、@Repository、@Service、@Controller、@ComponentScan是Spring注解
所以@ComponentScan只能扫描@Component、@Repository、@Service、@Controller

@Mapper、@MapperScan是Mybatis注解,所以@MapperScan只能扫描@Mapper,所以要是在Mapper层要是使用了@Mapper注解,那么SpringBoot的@ComponentScan是扫描不到的,必须在启动类上面加上@MapperScan扫描。

2.2解决方案:

后面查我的Mapper类的代码,我发现mapper的代码我是用@Mapper来标准的,所以这样@ComponentScan扫描不到我们的Mapper类,那么我们就得在启动类上加上一个@MapperScan("com.xxx.mapper")即可解决问题。

等于说这个testSpringBoot里面这个TestSpringBootApplication这个类是和下面的test的类对应的

所以在这个TestSpringBootApplication下一定要加上一个@MapperScan

2.3解决后结果截图

  • 25
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值