SpringBoot获取数据源出现错误:Failed to load ApplicationContext

本文解析了SpringBoot框架单元测试中出现的FailedtoloadApplicationContext错误原因,主要由于配置文件写错或配置项缺失,特别是mappers文件夹下的UserMapper.xml文件不完整。提供了两种解决方案:删除mybatis的mapper-locations配置或补全mapper配置文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SpringBoot框架单元测试出现错误:Failed to load ApplicationContext,一般都可能是配置文件写错了,或者是配置文件中配置的东西在项目中没有从而导致的错误。

spingboot配置文件是application.properties文件。

我的单元测试错误代码:

java.lang.IllegalStateException: Failed to load ApplicationContext

Caused by: 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: 
'file [D:\WorkSpace\questions\storeExec\target\classes\mappers\UserMapper.xml]'; 
nested exception is org.apache.ibatis.builder.BuilderException: 
Error creating document instance.  
Cause: org.xml.sax.SAXParseException; 文件提前结束。

Caused by: 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: 'file [D:\WorkSpace\questions\storeExec\target\classes\mappers\UserMapper.xml]'; 
nested exception is org.apache.ibatis.builder.BuilderException:
 Error creating document instance.  Cause: org.xml.sax.SAXParseException; 文件提前结束。

Caused by: org.apache.ibatis.builder.BuilderException: 
Error creating document instance.  Cause: org.xml.sax.SAXParseException; 文件提前结束。

Caused by: org.xml.sax.SAXParseException; 文件提前结束。

然后查看错误代码,发现一句:[D:\WorkSpace\questions\storeExec\target\classes\mappers\UserMapper.xml]。

最终错误原因是我的mappers文件夹下的UserMapper.xml文件中代码没有写全,从而导致SpringBoot在初始化时,不能读取到配置信息。

解决方案:

方案一:要么先把配置文件中的mybatis的mapper-locations先删掉,等要使用时在添加,并且还要添加相应的mapper相关的xml文件。

 

方案二:补全相关的mapper配置文件。

然后在启动获取数据源,测试结果如下:

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Mr.小朱同学

随心赞赏,助力前行

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值