我想使用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”);
答案 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 Loader的Spring Reference:
Resource template = ctx.getResource("some/resource/path/myTemplate.txt);
将会返回什么
ClassPathResource
;如果相同 方法是针对a执行的FileSystemXmlApplicationContext
例如,你会回来的FileSystemResource
。为一个WebApplicationContext
,你会得到的 返回ServletContextResource
,然后 等等。因此,您可以加载资源 适合特定的时尚 应用程序上下文。
因此,这是检索资源的首选方法。
或者,因为/WEB-INF/
在技术上属于类路径,所以您可以使用classpath:
前缀(根据您的注释)或使用ClassPathXmlApplicationContext
(它将自动返回类路径资源)。
也没有必要加双正斜杠。不知道你为什么这样做。也许是双反斜杠的延续,这是必要的吗?