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配置文件。
然后在启动获取数据源,测试结果如下: