一、依赖导入错误
如果发现你的注解报错,或者存在无法自动注入bean的错误,那么你就要看看是不是你的依赖导入错误:
- 错误重现:导入错误依赖
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2022-03-31 10:58:52.140 ERROR 1040 --- [ main] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.example.demo.DemoApplication#MapperScannerRegistrar#0': Initialization of bean failed; nested exception is java.lang.NoClassDefFoundError: org/apache/ibatis/session/SqlSessionFactory
- 查看自己导入的依赖是否有问题
如果发现你导入的依赖是下面这个,恭喜你中奖了。(此时只要把下面的错误的改成上面这个正确依赖就行)
依赖版本可以适当调整
PS:每一次修改pom文件都要点右上角依赖刷新按钮,否则修改不会生效
二、项目启动错误
如果你的依赖没有问题,启动项目的时候发现报错,那么可能是你的mapper包没有被扫描
Description:
Field userMapper in com.example.demo.service.impl.UserServiceimpl required a bean of type 'com.example.demo.mapper.UserMapper' that could not be found.
The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.example.demo.mapper.UserMapper' in your configuration.
报错样式:(错误类型:扫描不到mapper类)
解决方案有两种:(选择其一即可,两者都加上也不会报错)
1、在你的UserMapper类上加@mapper注解;
2、在你的启动类DemoApplication上加@MapperScan("com.example.demo")注解;![](https://i-blog.csdnimg.cn/blog_migrate/640b6272af95a0e7edf116bc464313c5.png)
三、项目运行错误
如果查看你的依赖也没有问题,注解也没有问题,启动项目的时候也没有报错,然后你信心百倍的去浏览器输入地址,发起请求;然后你会surprise的发现报错500
报错代码:
org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.example.demo.mapper.UserMapper.save
这个时候你肯定在想,我的mapper类明明有啊,我又不瞎,为什么电脑找不到呢,那一定是电脑瞎了;
没错,你的mapper类是找到了,但是你编写的增删改查数据库执行代码找不到,也就是说到不到你的mapper.xml文件,这个时候你就要看你的application.yml(或application.properties)文件是不是缺少了以下配置:
mybatis:
mapper-locations: classpath:mapping/*.xml
type-aliases-package: com.example.demo.entity
假如你的xml文件不想放在resources文件下面,偏偏要放在src.main.java文件下面,那么此时此刻系统一定又懵逼了,找不到你的xml文件,那么在pom.xml中添加以下配置,告诉idea,在编译的时候将src/main/java下的xml一起打包进class文件夹中,这样也就不会报Invalid bound statement (not found)错误了:
<build>
<!-- 项目打包时会将java目录中的*.xml文件也进行打包 -->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
然后在yml文件中修改对应位置,最好清理一下缓存,刷新一下maven,重新启动程序。
当你把以上所有错误都排除了以后,此时你一定发现头发又少了几根;那么你的项目也可以正确的运行起来了。(如果此时你的项目还没有运行起来,那就要看看你的sql连接是否正确,你的mapper.xml文件编写是否正确)
(当你的头发变少了,你也就变强了!)
项目地址:
Demo Project: 这个仓库用于存放日常练手的项目或者某一项技术的框架
https://gitee.com/yan_hongwei/demo02.git 测试环境:idea2020,jdk11,maven3.6.3