Spring按名称与类型获取Bean报错FileNotFoundException问题求助
Spring配置文件找不到问题解决方案
报错核心信息:
Exception in thread "main" org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [org/pus/learn/src/main/resources/applicationBean.xml]; nested exception is java.io.FileNotFoundException: class path resource [org/pus/learn/src/main/resources/applicationBean.xml] cannot be opened because it does not exist
错误原因
- 构造方法使用错误:你调用的
ClassPathXmlApplicationContext(String configLocation, Class<?> clazz)是相对路径加载重载,第二个入参的类所在包会作为配置文件的查找根路径,因此Spring会到org/pus/learn包路径下查找applicationBean.xml,和你文件的实际存放位置不匹配。 - 资源路径认知错误:标准Maven/Gradle项目中
src/main/resources是类路径资源根目录,编译后该目录下的文件会直接输出到类路径根,不会保留src/main/resources层级,报错信息中出现的该路径本身就是错误的查找路径。
修复方案
方案一(推荐):类路径根直接加载
删除构造方法的第二个入参Coach.class,修改代码如下即可:
package org.pus.learn; import org.springframework.context.support.ClassPathXmlApplicationContext; public class SpringTestApp { public static void main(String...args){ // 仅传入配置文件名,Spring会从类路径根直接查找 ClassPathXmlApplicationContext test = new ClassPathXmlApplicationContext("applicationBean.xml"); Coach testCoach = test.getBean("myCoach", Coach.class); System.out.println(testCoach.giveAdvice()); } }
该方案适配你当前的项目结构:
方案二:适配相对路径规则
如果你要保留原有构造方法的写法,需要将applicationBean.xml移动到src/main/resources/org/pus/learn目录下,和Coach类的包路径一一对应,即可正常加载配置文件。
内容的提问来源于stack exchange,提问作者sankardev51
相关产品推荐
相关产品推荐

