在给Spring项目做单元测试时,运行提示了如下报错信息:

class path resource [applicationContext.xml] cannot be  opened  because it  dose not exist

IDEA中Spring配置错误:class path resource [.xml] cannot be opened because it does not exist_spring

报错信息意思是没有找到你的.xml配置文件

原代码如下:

@Test
public void findById(){
//获取spring容器
ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
//从容器中拿到所需的dao的代理对象
ItemsDao itemsDao=ac.getBean(ItemsDao.class);
//调用方法
Items items=itemsDao.findById(1);
System.out.println(items.getName());
}

applicationContest.xml文件内容:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">

<!-- dao层配置文件开始-->
<!--配置连接池-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///practice"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>

<!--配置生产SqlSession对象的工厂-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!-- 扫描pojo包,给包下所有pojo对象起别名-->
<property name="typeAliasesPackage" value="com.itheima.domain"/>
</bean>

<!-- 扫描接口包路径,生成包下所有接口的代理对象,并且放入spring容器中 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.itheima.dao"/>
</bean>
<!-- dao层配置文件结束-->

</beans>

由于使用的是下面这种方式来获取配置文件的,ClassPathXmlApplicationContest()方法是在其所在的目录中寻找.xml配置文件

注意:这里指的是编译后的.class文件所在的目录,不是.java文件

ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");

出现异常时,我的项目目录结构是下面这样:

IDEA中Spring配置错误:class path resource [.xml] cannot be opened because it does not exist_mvc_02

在网上查资料后发现,是applicationContest.xml文件位置的问题,必须把spring的配置文件applicationContest.xml放到系统根目录下,即项目层次为下图:

IDEA中Spring配置错误:class path resource [.xml] cannot be opened because it does not exist_mvc_03

再次编译后,运行成功。