现象:IDEA,spring项目,报错class path resource [applicationContext.xml] cannot be opened because it does not exist
这样的异常 ,意思就是没有找到 .xml 配置文件
原因
使用如下操作
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
来获取配置文件
ClassPathXmlApplicationContext( ) 方法是在.class文件所在的目录中寻找 .xml 配置文件
注意: 这里指的是编译后的 .class 文件所在的目录,不是 .java 文件的目录
出现异常时,我的项目结构时这样的:
此时 resources/applicationContext.xml 文件在 src 目录下
造成异常的原因是 IDEA 默认的项目结构导致的,它将 .java 文件和 .class 文件分开存放,.java文件存于 src 中,.class 文件存于 target 中
因此,ClassPathXmlApplicationContext( ) 方法无法找到 applicationContext.xml
解决方法
将recourses文件夹标记为资源文件夹!
点击 File -> Project Structure(或快捷键 Ctrl+Alt+Shift+S)