本文主要是介绍测试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")即可解决问题。


2.3解决后结果截图

这篇关于测试SpringBoot的时候报错mapper未装载的解决方案:的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!