Search code examples
javaspringxml-configuration

class path resource cannot be opened because it does not exist when I load context manually


I have the following webApp folder structure:

enter image description here

I want to load spring context manually.

I wrote the following code:

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

When the code above invokes I see the folowing exception message:

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

How to rewrite my code to avoid this exception?

P.S. I don't want to move my xml file.

P.P.S.

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

doesn't work too although in web.xml was written

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

and it works


Solution

  • When you provide this location

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

    The resource is resolved relative to the Servlet context path.

    When you provide

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

    you're telling Spring to find the given resource on the classpath. In your case, it probably isn't there (WEB-INF is not typically added to the classpath afaik).

    Either add it to the classpath or move the applicationContext.xml file to a different location on the classpath and use that path in your constructor.