本文介绍了在Spring中获取FileNotFoundException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用BeanFactory创建bean,但我得到一个例外: java.io.FileNotFoundException:\\WEB-INF \ businesscaliber-servlet.xml

I want to create bean using BeanFactory, but I am getting an exeception: java.io.FileNotFoundException: \\WEB-INF\businesscaliber-servlet.xml.

Resource res = new FileSystemResource("//WEB-INF//businesscaliber-servlet.xml");
BeanFactory factory = new XmlBeanFactory(res);
if (factory != null && beanId != null) {
    obj = factory.getBean(beanId);
}

他使用此工作

ApplicationContext ctx = new FileSystemXmlApplicationContext(classpath *:/ WEB-INF / businesscaliber-servlet.xml);

ApplicationContext ctx = new FileSystemXmlApplicationContext("classpath*:/WEB-INF/businesscaliber-servlet.xml");

推荐答案

我认为你需要指定一个绝对路径,而不是指向。

I believe you need to specify an absolute path and not a Web application relative path to FileSystemResource.

尝试使用。

唯一的问题是你需要所以:

The only issue is you need the ServletContext so:

ServletContext servletContext = ...
Resource res = new ServletContextResource(servletContext,
  "/WEB-INF/businesscaliber-servlet.xml");
BeanFactory factory = new XmlBeanFactory(res);
if (factory != null && beanId != null) {
    obj = factory.getBean(beanId);
}

值得注意的是,理想情况下你会从。来自 (它将自动返回类路径资源)。

Alternatively since /WEB-INF/ is technically in the classpath you can use the classpath: prefix (as per your comment) or use ClassPathXmlApplicationContext (which will automatically return classpath resources).

此外,无需添加双正斜杠。不知道你为什么要这样做。也许是双反斜杠的延续,这是必要的吗?

Also theres no need to put double forward slashes in. Not sure why you're doing this. Perhaps a holdover from double backslashes, which are necessary?

这篇关于在Spring中获取FileNotFoundException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 15:33