gpt4 book ai didi

java - 在 Spring 中获取 FileNotFoundException

转载 作者:行者123 更新时间:2023-11-29 06:23:22 25 4
gpt4 key购买 nike

我想使用 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");

最佳答案

我相信您需要指定一个绝对路径,而不是 FileSystemResource 的 Web 应用程序相对路径.

尝试使用 ServletContextResource相反。

Resource implementation for ServletContext resources, interpreting relative paths within the web application root directory.

唯一的问题是您需要 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);

What would be returned would be a ClassPathResource; if the same method was executed against a FileSystemXmlApplicationContext instance, you'd get back a FileSystemResource. For a WebApplicationContext, you'd get back a ServletContextResource, and so on.

As such, you can load resources in a fashion appropriate to the particular application context.

所以这是检索资源的首选方法。

或者,由于 /WEB-INF/ 在技术上位于类路径中,您可以使用 classpath: 前缀(根据您的评论)或使用 ClassPathXmlApplicationContext (这将自动返回类路径资源)。

也没有必要放入双正斜线。不知道你为什么要这样做。也许是双反斜杠的遗留问题,这是必要的?

关于java - 在 Spring 中获取 FileNotFoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2076198/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com