您的位置:首页 > 编程语言 > Java开发

新建java项目使用this.classLoader.getResourceAsStream方法导入xml文件时报找不到文件原因

2016-08-02 23:29 986 查看
代码如下时:

public class springStudy {

public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml");//读取bean.xml中的内容
Person p = ctx.getBean("person",Person.class);//创建bean的引用对象
   p.info();
}

}

调用的spring标黄部分源码:

public InputStream getInputStream() throws IOException {
InputStream is;
if (this.clazz != null) {
is = this.clazz.getResourceAsStream(this.path);
}
else {
is = this.classLoader.getResourceAsStream(this.path);
}
if (is == null) {
throw new FileNotFoundException(
getDescription() + " cannot be opened because it does not exist");
}
return is;
}

出现报错,在classpath下找不到这个文件

信息: Loading XML bean definitions from class path resource [bean.xml]

Exception in thread "main" org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [bean.xml]; nested exception is java.io.FileNotFoundException: class path resource [bean.xml] cannot be opened
because it does not exist
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:341)

初步判断是路径不对,网上找了一圈关于这个方法的解释,有绝对路径和相对路径的说法等等。

工程结构如下:

上述代码使用的方法是找到所加载的类的路径,所以找到的是java工程下默认的bin目录,而bin目录下只有一个springStudy的文件夹,所以报找不到bean.xml的错误。

修改代码为:

ApplicationContext ctx = new ClassPathXmlApplicationContext("springStudy/bean.xml");//读取bean.xml中的内容

问题解决!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐