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

java.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");



  • 17
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值