最近按照网上的demo做了一个springboot的小项目,为了整合springboot和mybatis+xml进行演示,但是在配置时一直报错,纠结了两个小时:
如下是启动springboot是的报错:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'cityDaoImpl': Unsatisfied dependency expressed through field 'sqlSessionTemplate'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sqlSessionTemplate' defined in class path resource [org/mybatis/spring/boot/autoconfigure/MybatisAutoConfiguration.class]: Unsatisfied dependency expressed through method 'sqlSessionTemplate' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [org/mybatis/spring/boot/autoconfigure/MybatisAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.ibatis.session.SqlSessionFactory]: Factory method 'sqlSessionFactory' threw exception; nested exception is org.springframework.core.NestedIOException: Failed to parse mapping resource: 'class path resource [mybatis-config.xml]'; nested exception is org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML. Cause: java.lang.NullPointerException
调试心得:
没经验的时候是从前往后一直查找,百度网上相关例子,总结起来,查找如下:
在网上看到了许多人都经历过类似的错误,归纳起来有:
- Application启动类放置位置问题
- 注解配置不完整,如Service实现类没有加@Service,Spring boot无法扫描等
- 配置文件等内容有误
- Jar包冲突
一个一个查找,第一个问题,因为引用别人的项目,所以不可避免的有些包名和结构发生变化,
1、检查application.properties文件中,关于mybatis.mapper-locations=classpath:mybatis-config.xml的问题,
当时一直以为这个classpath是在加载时去mybatis-config.xml中进行CityMapper的加载,所以在配置mybatis-config.xml时,
一直找不到CityMapper.xml这个文件,导致Error parsing Mapper XML. Cause: java.lang.NullPointerException的问题,所以解决办法,直接在mybatis.mapper-locations=classpath:mybatis-config.xml更改为mybatis.mapper-locations=classpath:mybatis/mapper/*.xml,跳过mybatis-config.xml,直接使用mybatis/mapper/*.xml进行xml的加载
2、在调试过程中,同样发现,Service实现类没有加@Service,导致Spring boot无法扫描,
两个小bug浪费了两个小时,对于springboot小白的我来说太心痛了