无法打开类路径资源,因为当我手动加载上下文时它不存在

时间:2015-06-05 22:02:07

标签: java spring xml-configuration

我有以下webApp文件夹结构:

enter image description here

我想手动加载弹簧上下文。

我写了以下代码:

ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");

当上面的代码调用时,我会看到以下异常消息:

java.io.FileNotFoundException: class path resource [applicationContext.xml] cannot be opened because it does not exist

如何重写我的代码以避免此异常?

P.S。 我不想移动我的xml文件。

P.P.S。

new ClassPathXmlApplicationContext("WEB-INF/applicationContext.xml")  

虽然在web.xml中写了

,但也不起作用
<context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>WEB-INF/applicationContext.xml</param-value>
</context-param>

并且有效

1 个答案:

答案 0 :(得分:0)

当您提供此位置时

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>WEB-INF/applicationContext.xml</param-value>
</context-param>

相对于Servlet上下文路径解析资源。

提供时

new ClassPathXmlApplicationContext("WEB-INF/applicationContext.xml")  

你告诉Spring在类路径上找到给定的资源。在你的情况下,它可能不存在(WEB-INF通常不会添加到类路径中)。

将其添加到类路径或将applicationContext.xml文件移动到类路径上的其他位置,并在构造函数中使用该路径。