在Spring中获取FileNotFoundException

时间:2010-01-16 04:28:44

标签: java spring

我想使用BeanFactory创建bean,但我得到了一个例外: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”);

1 个答案:

答案 0 :(得分:3)

我认为您需要指定绝对路径,而不是指向FileSystemResource的Web应用程序相对路径。

请尝试使用ServletContextResource

  

Resource实施   ServletContext资源,   解释内部的相对路径   Web应用程序根目录。

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

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);
}

值得注意的是,理想情况下,您会从ApplicationContext中检索此内容。来自4.4 Resource LoaderSpring Reference

Resource template = ctx.getResource("some/resource/path/myTemplate.txt);
     

将会返回什么   ClassPathResource;如果相同   方法是针对a执行的   FileSystemXmlApplicationContext   例如,你会回来的   FileSystemResource。为一个   WebApplicationContext,你会得到的   返回ServletContextResource,然后   等等。

     

因此,您可以加载资源   适合特定的时尚   应用程序上下文。

因此,这是检索资源的首选方法。

或者,因为/WEB-INF/在技术上属于类路径,所以您可以使用classpath:前缀(根据您的注释)或使用ClassPathXmlApplicationContext(它将自动返回类路径资源)。

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

相关问题