java.io.FileNotFoundException: class path resource [XXXXX.xml] cannot be opened

来源:互联网 发布:java中断 原理 编辑:程序博客网 时间:2024/05/29 02:32

ava.io.FileNotFoundException: class path resource [beans.xml] cannot be opened because it does not exit.

在用maven管理的spring项目中做单元测试时候,加载不了spring的配置文件。出现该问题的原因是,用maven创建的项目,必须把spring的配置文件beans.xml或者applicationContext.xml放到系统根目录下,做单元测试时候用

ApplicationContext applicationContext=new ClassPathXmlApplicationContext("beans.xml");    Girl girl=(Girl)applicationContext.getBean("girl");
才能正确加载spring的配置文件,才能正确获取bean。不知道这个定律在其他电脑的环境下是否适合,撸主在两台计算机上都是通过这种方式配好的。

maven项目的系统根目录默认是src/main/java和src/main/resources,而不是src,所以beans.xml文件必须放到 src/main/java和src/main/resources 下面的文件夹或者包中,否则就会报上面的错误: java.io.FileNotFoundException: class path resource [beans.xml] cannot be opened because it does not exit.

还有一点,要注意的是,如果beans.xml不是直接放到了 src/main/java和src/main/resources路径下,在读取beans文件时候,还要加上路径,如beans.xml放在了 src/main/java/conf路径下,那么加载时候要这样写:

ApplicationContext applicationContext=new ClassPathXmlApplicationContext("conf/beans.xml");

否则就会报错: java.io.FileNotFoundException: class path resource [beans.xml] cannot be opened because it does not exit.

而下面这种写法,是把 beans.xml直接放到了 src/main/java和src/main/resources路径下 

ApplicationContext applicationContext=new ClassPathXmlApplicationContext("beans.xml");
0 0