Kevin Morocco
Kevin Morocco

Reputation: 179

Loading spring XML from location different from classpath

I am trying to read spring xml using ClassPathXmlApplicationContext class as below.

    ApplicationContext context = new ClassPathXmlApplicationContext("file:../WebContent/WEB-INF/dispatcher-servlet.xml");
    Service service = (Service ) context.getBean("service");

But I am getting FileNotFound exception. dispatcher-servlet.xml is located under WebContent/WEB-INF/dispatcher-servlet.xml. If I move the file to Src folder, it works fine.

I tried different ways like

    ApplicationContext context = new ClassPathXmlApplicationContext("classpath:../WebContent/WEB-INF/dispatcher-servlet.xml");

 ApplicationContext context = new ClassPathXmlApplicationContext("/WEB-INF/dispatcher-servlet.xml");

But these don't work. Can someone provide some inputs.

Upvotes: 0

Views: 1194

Answers (2)

Vidya
Vidya

Reputation: 30320

Try this in your web.xml:

<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>WEB-INF/dispatcher-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

Or use ServletContextResource if you need to do this in code. See here.

Upvotes: 0

Akira
Akira

Reputation: 4071

from the Spring documentation:

ApplicationContext ctx = new FileSystemXmlApplicationContext("conf/appContext.xml");

Upvotes: 1

Related Questions